下面的代码将生成一个条形图,每个条形图上方均带有数据标签(底部显示)。有什么方法可以使y轴上的刻度变成百分比(在此图表中,将为0%,20%等)?
我设法通过将条形高度与“%”串联来获得每个条形上方的数据标签,以描绘百分比。
import numpy as np
import matplotlib.pyplot as plt
n_groups = 5
Zipf_Values = (100, 50, 33, 25, 20)
Test_Values = (97, 56, 35, 22, 19)
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
rects1 = plt.bar(index, Zipf_Values, bar_width, color='g',
label='Zipf', alpha= 0.8)
rects2 = plt.bar(index + bar_width, Test_Values, bar_width, color='y',
label='Test Value', alpha= 0.8)
plt.xlabel('Word')
plt.ylabel('Frequency')
plt.title('Zipf\'s Law: Les Miserables')
plt.xticks(index + bar_width, ('The', 'Be', 'And', 'Of', 'A'))
plt.legend()
for rect in rects1:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 0.99*height,
'%d' % int(height) + "%", ha='center', va='bottom')
for rect in rects2:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 0.99*height,
'%d' % int(height) + "%", ha='center', va='bottom')
plt.tight_layout()
plt.show()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句