如何在 Matplotlib 中显示条形图上方的百分比?


要在 Matplotlib 中显示条形图上方的百分比,我们可以采取以下步骤:

  • 设置图形大小并调整子图之间和周围的填充。
  • 创建 x 和 y 数据点;初始化一个变量,宽度
  • 使用 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()

输出

更新日期:2021 年 6 月 3 日

3K+ 视图

开启你的 职业生涯

完成课程认证

开始
广告