python bar图 百分比_如何将条形图值更改为百分比(Matplotlib)

下面的代码生成一个条形图,每个条形图上方都有数据标签(如下图所示)。有没有办法把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 bar图 百分比_如何将条形图值更改为百分比(Matplotlib)

Original: https://blog.csdn.net/weixin_33662430/article/details/113960813
Author: 萨缪尔
Title: python bar图 百分比_如何将条形图值更改为百分比(Matplotlib)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/768049/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球