如何在 Matplotlib 中将条形图值更改为百分比?
matplotlibpythondata visualization更新于 2025/12/17 6:04:17
要在 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()
输出
它能产生以下输出 −

相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

