如何在条形图的条形上方写入文本(Python Matplotlib)?
matplotlibpythondata visualization更新于 2025/6/1 13:32:17
要在条形图的条形上方写入文本,我们可以采取以下步骤
- 设置图形大小并调整子图之间和周围的填充。
- 创建年份、人口和x的列表。初始化宽度变量。
- 使用 subplots() 方法创建一个图形和一组子图。
- 设置 ylabels、title、xtickas 和 xticklabels。
- 使用 bar() 方法,使用 x、population 和宽度数据绘制条形图。
- 使用 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
years = [1901, 1911, 1921, 1931, 1941, 1951, 1961, 1971, 1981, 1991, 2001, 2011]
population = [237.4, 238.4, 252.09, 251.31, 278.98, 318.66, 361.09,
439.23, 548.16, 683.33, 846.42, 1028.74]
x = np.arange(len(years)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
ax.set_ylabel('Population(in million)')
ax.set_title('Years')
ax.set_xticks(x)
ax.set_xticklabels(years)
pps = ax.bar(x - width / 2, population, width, label='population')
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/

