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

Matplotlib中如何自动对齐同一绘图的两个图例标题Y轴位置?

如何自动对齐两个高度不同图例的Y轴起始标题位置?

我用Matplotlib绘制的图表里有两个高度不同的图例,想让它们的标题在Y轴上的起始位置对齐。目前我只能手动调整bbox_to_anchor参数(比如bbox_to_anchor=(-0.1, -0.3)),但每次内容微调都得重新设置,有没有自动实现的方法?

原代码示例

fig = plt.figure(1)
ax = fig.add_subplot(1, 1, 1)
xticks = mtick.FormatStrFormatter(fmt)
yticks = mtick.FormatStrFormatter(fmt)
x1 = plt.scatter([1,2],[2,3], color='b')
x2 = plt.scatter([2,3],[4,3], color='r')
x3 = plt.scatter([1,3],[4,5], color='k')
x4 = plt.scatter(0, 0, color='white')
marker1 = 'marker 1'
marker2 = 'marker 2'
marker3 = 'marker 3'
plt.xlabel("x axis")
plt.ylabel("y axis")
marker4 = ('some text that needs to go here too'+'\n'+'and is very important and just way too long so that it wont ever look good')
legend_two = plt.legend([x1, x4],[marker1, marker4],fontsize=8,
                           title='some other title', title_fontsize=10,
                           bbox_to_anchor=(0.5, -0.3), ncol=1, loc="center left", borderaxespad=0)
plt.legend([x1,x2,x3], [marker1,marker2,marker3], fontsize=8,
           title='some title', title_fontsize=10,
           bbox_to_anchor=(-0.1, -0.3), ncol=3, loc="center left", borderaxespad=0)
plt.gca().add_artist(legend_two)
plt.tight_layout()
plt.show()

自动对齐解决方案

核心逻辑是获取两个图例标题的像素位置,计算偏移量后自动调整图例位置,无需手动设置Y轴参数:

import matplotlib.pyplot as plt
import matplotlib.ticker as mtick

# 补充原代码缺失的格式定义
fmt = "%d"

fig = plt.figure(1)
ax = fig.add_subplot(1, 1, 1)
# 原代码漏了应用格式的步骤,补上
xticks = mtick.FormatStrFormatter(fmt)
yticks = mtick.FormatStrFormatter(fmt)
ax.xaxis.set_major_formatter(xticks)
ax.yaxis.set_major_formatter(yticks)

x1 = plt.scatter([1,2],[2,3], color='b')
x2 = plt.scatter([2,3],[4,3], color='r')
x3 = plt.scatter([1,3],[4,5], color='k')
x4 = plt.scatter(0, 0, color='white')

marker1 = 'marker 1'
marker2 = 'marker 2'
marker3 = 'marker 3'
plt.xlabel("x axis")
plt.ylabel("y axis")

marker4 = ('some text that needs to go here too'+'\n'+'and is very important and just way too long so that it wont ever look good')

# 先创建图例,临时设置Y轴位置为0,后续自动调整
legend_two = plt.legend([x1, x4],[marker1, marker4],fontsize=8,
                       title='some other title', title_fontsize=10,
                       bbox_to_anchor=(0.5, 0), ncol=1, loc="center left", borderaxespad=0)
main_legend = plt.legend([x1,x2,x3], [marker1,marker2,marker3], fontsize=8,
                       title='some title', title_fontsize=10,
                       bbox_to_anchor=(-0.1, 0), ncol=3, loc="center left", borderaxespad=0)
plt.gca().add_artist(legend_two)

# 强制渲染图表,确保能获取准确的元素坐标
fig.canvas.draw()

# 获取两个图例标题的Y轴像素坐标
main_title_y = main_legend.get_title().get_window_extent().y
two_title_y = legend_two.get_title().get_window_extent().y

# 计算偏移量,转换为Matplotlib使用的英寸单位
y_offset = (main_title_y - two_title_y) / fig.dpi

# 调整第二个图例的Y轴位置,让标题对齐
current_bbox = legend_two.get_bbox_to_anchor().get_points()
current_bbox[0][1] += y_offset
legend_two.set_bbox_to_anchor(current_bbox, transform=fig.transFigure)

plt.tight_layout()
plt.show()

关键说明

  • get_window_extent():获取元素的像素边界框,用于精准获取标题的位置
  • fig.canvas.draw():必须先渲染图表,否则无法获取真实的元素坐标
  • 偏移量转换:Matplotlib的bbox_to_anchor使用英寸单位,需要将像素差除以DPI转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 01:18:14