【问题标题】:How To Change Bar Chart Values to Percentages (Matplotlib) [duplicate]如何将条形图值更改为百分比(Matplotlib)[重复]
【发布时间】: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


    【解决方案1】:

    您需要为 y 轴指定 a custom formatter,这只会将百分比符号附加到所有现有标签。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-10
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      相关资源
      最近更新 更多