You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Matplotlib图表下方左对齐添加固定位置文本的方法

问题

我希望在Matplotlib绘制的图表下方添加包含数据来源的文本,要求文本位于图像左侧边缘(最长y轴刻度下方),且与x轴保持固定垂直距离。

我目前的实现方法:

import matplotlib.pyplot as plt

country = ['Portugal','Spain','Austria','Italy','France','Federal Republic of Germany']
value = [6,8,10,12,14,25]

plt.figure(figsize=(4,4))
plt.barh(country,value)
plt.xlabel('x-axis')
plt.text(-18,-2.5,'Source: blablablablablablablablablablablablablablablablabla',ha='left')

当前问题:针对不同图表,需要手动尝试调整plt.text()的x、y参数值,无法自动适配。

请问是否有更优的实现方式?

解决方案

可以利用Matplotlib的轴坐标变换实现自动定位,无需手动计算或调试坐标参数:

方法1:基于轴相对坐标的通用定位

轴坐标的范围是(0,0)(轴左下角)到(1,1)(轴右上角),直接指定文本在轴坐标系中的位置,不受数据范围影响:

import matplotlib.pyplot as plt

country = ['Portugal','Spain','Austria','Italy','France','Federal Republic of Germany']
value = [6,8,10,12,14,25]

# 使用面向对象的绘图方式(更灵活)
fig, ax = plt.subplots(figsize=(4,4))
ax.barh(country, value)
ax.set_xlabel('x-axis')

# 定位参数说明:
# x=0 对应轴左侧边缘;y=-0.15 表示在轴底部下方,距离为轴高度的15%
# transform=ax.transAxes 启用轴相对坐标
ax.text(0, -0.15, 'Source: blablablablablablablablablablablablablablablablabla', 
        ha='left', transform=ax.transAxes)

plt.tight_layout()  # 自动调整边距,避免文本被截断
plt.show()

方法2:对齐y轴刻度左侧的精准定位

如果需要严格对齐最长y轴刻度的左侧(而非轴边缘),可以结合数据坐标与轴坐标实现:

import matplotlib.pyplot as plt

country = ['Portugal','Spain','Austria','Italy','France','Federal Republic of Germany']
value = [6,8,10,12,14,25]

fig, ax = plt.subplots(figsize=(4,4))
ax.barh(country, value)
ax.set_xlabel('x-axis')

# 获取y轴刻度的最左侧数据坐标
y_tick_left = ax.get_ylim()[0]
# 使用x轴变换:x用数据坐标,y用轴相对坐标
ax.text(y_tick_left, -0.15, 'Source: blablablablablablablablablablablablablablablablabla', 
        ha='left', transform=ax.get_xaxis_transform())

plt.tight_layout()
plt.show()

核心优势

  • 无需手动调整坐标参数,自动适配不同数据范围的图表;
  • 垂直距离通过轴高度的百分比控制,保持固定比例;
  • plt.tight_layout()确保文本始终在图表可见区域内。

内容的提问来源于stack exchange,提问作者dirk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:05:18