简体   繁体   English

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

[英]How To Change Bar Chart Values to Percentages (Matplotlib)

The code below generates a barchart with data labels above each bar (pictured at the bottom). 下面的代码生成一个条形图,每个条形图上方都有数据标签(如下图所示)。 Is there any way to make the ticks on the y axis into percentages (in this chart, would be 0%, 20%, etc.)? 有没有办法让y轴上的刻度变成百分比(在这个图表中,将是0%,20%等)?

I managed to get the data labels above each bar to depict percentages by concatenating the bar height with "%". 我设法通过将条形高度与“%”连接来获取每个条形图上方的数据标签以描绘百分比。

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()

图形

You will want to specify a custom formatter for the y axis which will simply append the percent symbol to all of your existing labels. 您需要为y轴指定自定义格式化程序 ,只需将百分比符号附加到所有现有标签。

from matplotlib.ticker import FuncFormatter

formatter = FuncFormatter(lambda y, pos: "%d%%" % (y))
ax.yaxis.set_major_formatter(formatter)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM