【发布时间】:2016-07-07 02:47:50
【问题描述】:
下面的代码会生成一个条形图,每个条形上方都有数据标签(如下图所示)。有什么方法可以将 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()
【问题讨论】:
标签: python matplotlib