如何在Matplotlib中设置条形标签居右并为其添加标题
实现Matplotlib水平条形图标签外置并添加列标题
可以实现,bar_label确实仅支持edge和center两种位置,但我们可以通过手动绘制标签+调整布局的方式达成需求,具体步骤如下:
示例代码
import pandas as pd import matplotlib.pyplot as plt # 示例数据(替换成你的DataFrame) df = pd.DataFrame({ 'name': ['Amy', 'Bob', 'Jane'], 'days': [1, 4, 2] }) fig, ax = plt.subplots() # 绘制水平条形图 bars = ax.barh(df['name'], df['days']) # 设置图表标题 ax.set_title("Days people showed up") # 调整图表右侧边距,为标签留出空间 plt.subplots_adjust(right=0.8) # 获取x轴最大刻度值,用来定位标签位置 max_x = ax.get_xlim()[1] # 给标签位置增加偏移量,确保在条形右侧空白区 label_x_pos = max_x + 0.2 # 手动为每个条形添加标签 for bar in bars: bar_width = bar.get_width() # 获取条形对应的数值 bar_y_center = bar.get_y() + bar.get_height() / 2 # 获取条形垂直中心位置 # 放置标签,垂直居中对齐 ax.text(label_x_pos, bar_y_center, f'{int(bar_width)}', va='center') # 添加"Count"列标题,位置与标签列对齐 count_title_y = ax.get_ylim()[1] + 0.1 ax.text(label_x_pos, count_title_y, 'Count', ha='center') # 扩展x轴右侧范围,避免标签被截断 ax.set_xlim(right=max_x + 0.6) plt.show()
关键步骤说明
- 调整边距:通过
plt.subplots_adjust(right=0.8)缩小图表主体宽度,右侧留出空白放置标签。 - 手动绘制标签:遍历每个条形,用
ax.text()将标签精准定位到条形右侧的空白区域,va='center'保证标签与条形垂直居中对齐。 - 添加列标题:用
ax.text()在标签列顶部放置"Count"标题,通过调整y轴位置与标签列对齐。 - 扩展x轴范围:避免标签超出图表可视区域,确保完整显示。
内容的提问来源于stack exchange,提问作者userneedhelp029848
相关产品推荐
相关产品推荐

