如何用Matplotlib或其他Python可视化库在柱状图柱内添加标签?
用户问题(翻译后)
我想要绘制如下示例图的柱状图,现有代码如下:
x = [0, 1, 2] y = [88909, 27155, 12897] plt.bar(x, y, tick_label = ['Pre-K, elementary, and middle', 'Secondary and high', 'Other, ungraded, and n/a or not reported'])目前我可以用
plt.text在柱内添加标签,但需要手动计算每个标签的坐标,请问有没有工具库可以自动完成该操作,我只需要提供标签字符串即可?
解决方案
无需额外库:Matplotlib原生实现
直接通过获取柱状条的属性自动计算坐标,循环添加标签,不用手动计算:
import matplotlib.pyplot as plt x = [0, 1, 2] y = [88909, 27155, 12897] tick_labels = ['Pre-K, elementary, and middle', 'Secondary and high', 'Other, ungraded, and n/a or not reported'] # 绘制柱状图并获取所有柱子对象 bars = plt.bar(x, y, tick_label=tick_labels) # 遍历每个柱子添加标签 for bar in bars: bar_height = bar.get_height() # 自动计算标签的居中坐标 label_x = bar.get_x() + bar.get_width() / 2 label_y = bar_height / 2 # 添加文本标签,设置居中对齐、白色字体 plt.text(label_x, label_y, f"{bar_height}", ha="center", va="center", color="white") plt.show()
更简洁:Seaborn + Matplotlib bar_label
Matplotlib 3.4及以上版本提供了bar_label方法,结合Seaborn可以快速实现自动标签:
import seaborn as sns import matplotlib.pyplot as plt x = ['Pre-K, elementary, and middle', 'Secondary and high', 'Other, ungraded, and n/a or not reported'] y = [88909, 27155, 12897] # 绘制柱状图 ax = sns.barplot(x=x, y=y) # 自动添加柱内居中标签,无需手动计算坐标 ax.bar_label(ax.containers[0], label_type="center", color="white") plt.show()
bar_label会自动处理坐标计算,label_type="center"指定标签放在柱子内部居中位置,你只需要传入对应数值即可完成标签添加。
内容的提问来源于stack exchange,提问作者JJJohn
相关产品推荐
相关产品推荐

