如何在Matplotlib水平条形图的多个条形内添加文本标注
为Matplotlib水平条形图添加内部数字文本
你目前的代码生成了水平条形图,想要在每个条形内部添加对应的数值文本,实现目标图的效果,可以通过遍历条形元素并添加文本标注来实现。
原代码
import pandas import matplotlib.pyplot as plt import numpy as np df = pandas.DataFrame(dict(graph=['Fruits & Vegetables','Bakery'], p=[round(0.942871692205*100,5), round(0.933348641475*100,5)], q=[round(0.941649166881*100,5),round(0.931458324883*100,5)], r=[round(0.940803376393*100,5),round(0.929429068047*100,5)], )) ind = np.arange(len(df)) width = 0.25 fig, ax = plt.subplots() ax.barh(ind, df.p, width, color='red', label='Accrate>=80') ax.barh(ind + width, df.q, width, color='green', label='Accrate>=79') ax.barh(ind + 2*width, df.r, width, color='blue', label='Accrate>=78') ax.set(yticks=ind + 2*width, yticklabels=df.graph, ylim=[2*width - 1, len(df)]) ax.legend(bbox_to_anchor=(1.1, 1.05)) plt.show()
修改后的代码(添加内部数字文本)
import pandas import matplotlib.pyplot as plt import numpy as np df = pandas.DataFrame(dict(graph=['Fruits & Vegetables','Bakery'], p=[round(0.942871692205*100,5), round(0.933348641475*100,5)], q=[round(0.941649166881*100,5),round(0.931458324883*100,5)], r=[round(0.940803376393*100,5),round(0.929429068047*100,5)], )) ind = np.arange(len(df)) width = 0.25 fig, ax = plt.subplots() # 绘制条形并保存返回的条形容器对象 bars_p = ax.barh(ind, df.p, width, color='red', label='Accrate>=80') bars_q = ax.barh(ind + width, df.q, width, color='green', label='Accrate>=79') bars_r = ax.barh(ind + 2*width, df.r, width, color='blue', label='Accrate>=78') # 封装添加文本的逻辑 def add_bar_labels(bars): for bar in bars: # 获取条形的长度(对应数值大小) bar_width = bar.get_width() # 获取条形垂直方向的中心位置 bar_y_center = bar.get_y() + bar.get_height() / 2 # 在条形内部靠右位置添加文本,白色字体增强可读性 ax.text(bar_width - 2, bar_y_center, f'{bar_width:.5f}', va='center', color='white', fontweight='bold') # 给三组条形分别添加文本标注 add_bar_labels(bars_p) add_bar_labels(bars_q) add_bar_labels(bars_r) ax.set(yticks=ind + 2*width, yticklabels=df.graph, ylim=[2*width - 1, len(df)]) ax.legend(bbox_to_anchor=(1.1, 1.05)) plt.show()
核心逻辑说明
- 调用
barh时保存返回的BarContainer对象,这是每组条形元素的集合 - 自定义
add_bar_labels函数遍历每个条形:bar.get_width()获取条形对应的数值(水平条形的长度即数值大小)bar.get_y() + bar.get_height()/2计算条形垂直方向的中心位置,保证文本垂直居中ax.text()在条形内部靠右位置添加文本,通过bar_width - 2调整文本与条形右侧的间距,避免超出条形
内容的提问来源于stack exchange,提问作者krishna kaushik
相关产品推荐
相关产品推荐

