如何在 Matplotlib 中在条形图上方显示百分比?
matplotlibpythondata visualization更新于 2025/6/3 17:48:17
要在 Matplotlib 中在条形图上方显示百分比,我们可以采取以下步骤 −
- 设置图形大小并调整子图之间和周围的填充。
- 创建 x 和 y 数据点;初始化变量 width。
- 使用 subplots() 方法创建一个图形和一组子图。
- 添加带有 x 和 y 数据点的条形图。
- 迭代条形图补丁;使用 text() 方法在条形图上放置文本。
- 要显示图形,请使用 show() 方法。
示例
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [1, 2, 3, 4, 5]
y = [3, 4, 2, 1, 3]
width = 0.35
fig, ax = plt.subplots()
pps = ax.bar(x, y, width, align='center')
for p in pps:
height = p.get_height()
ax.text(x=p.get_x() + p.get_width() / 2, y=height+.10,
s="{}%".format(height),
ha='center')
plt.show()
输出

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

