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

本文展示了一段Python代码,该代码生成一个条形图,并在每个条形上显示百分比标签。代码中,使用了matplotlib库创建条形图,然后通过在每个条形的顶部添加百分比文本来表示频率的百分比。条形图的Y轴表示频率,X轴表示单词,数据包括Zipf值和Test值。
摘要由CSDN通过智能技术生成

下面的代码生成一个条形图,每个条形图上方都有数据标签(如下图所示)。有没有办法把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()

50e1e03854aae1f234aa44c0edfcf8ab.png

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值