如何在 Matplotlib 中将条形图值更改为百分比?

要将条形图值更改为 matplotlib 中的百分比,我们可以采取以下步骤

步骤

  • 设置图形大小并调整子图之间和周围的填充。

  • 列出频率列表。

  • 创建新地物或激活现有地物。

  • bar()使用方法制作条形图。

  • 迭代条形图并找到每个补丁的高度,并使用annotate()方法将值以百分比表示。

  • 要显示图形,请使用Show()方法。

示例

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

frequencies = [7, 8, 5, 3, 6]

plt.figure()

p1 = plt.bar(np.arange(len(frequencies)), frequencies)

for rect1 in p1:
    height = rect1.get_height()
    plt.annotate( "{}%".format(height),(rect1.get_x() + rect1.get_width()/2, height+.05),ha="center",va="bottom",fontsize=15)

plt.show()
输出结果

它将产生以下输出 -