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

如何在Matplotlib图表右上角并排对齐两个文本框?

在Matplotlib右上角放置并排衔接的文本框

要让两个文本框在图表右上角边缘衔接,核心是获取第一个文本框的实际边界位置,再以此定位第二个文本框。当前代码仅使用文本的坐标位置,未考虑文本框宽度,导致重叠。以下是修正后的实现:

修改后的完整代码

import numpy as np
import matplotlib.pyplot as plt

# data
x = np.linspace(-10, 10, 51)
shrink_factors = np.linspace(1, 0, x.size)
y1 = shrink_factors*np.sin(np.exp(-x))
y2 = shrink_factors*np.cos(np.exp(-x))

# get plot parameters
xlim = [np.min(x), np.max(x)]
ylim = [0, 1.125*np.max([np.max(y1), np.max(y2)])]
facecolors = ("red", "blue")
(color1, color2) = facecolors
label1 = "Label 1"
label2 = "Label 2"
text1 = "RED 1"
text2 = "BLUE 2"
text_background_color = "gainsboro"
text_size = 12
figsize = (12, 7)
# figsize = (7, 12)

# initialize plot
fig, ax = plt.subplots(figsize=figsize)

# plot data
ax.plot(x, y1, color=color1, label=label1)
ax.plot(x, y2, color=color2, label=label2)
ax.grid(color="black", linestyle=":", alpha=0.3)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
fig.legend(mode="expand", loc="lower center", ncol=2)

# 先绘制右侧的文本框(BLUE 2),右对齐到右上角
text_box2 = ax.text(0.95, 0.95, text2, 
                    color=color2, 
                    fontsize=text_size, 
                    horizontalalignment="right", 
                    verticalalignment="top", 
                    transform=ax.transAxes)
text_box2.set_bbox({"facecolor": text_background_color, "edgecolor": "black"})

# 获取文本框2的显示范围,转换为Axes坐标
fig.canvas.draw()  # 必须先绘制才能获取准确的bbox
bbox2 = text_box2.get_window_extent().transformed(ax.transAxes.inverted())
# 文本框2的左边缘x坐标就是文本框1的右对齐位置
text_box1 = ax.text(bbox2.x0, 0.95, text1, 
                    color=color1, 
                    fontsize=text_size,
                    horizontalalignment="right", 
                    verticalalignment="top", 
                    transform=ax.transAxes)
text_box1.set_bbox({"facecolor": text_background_color, "edgecolor": "black"})

# finish plot
plt.show()
plt.close()

关键说明

  1. 先绘制右侧文本框:确保它的右边缘对齐到Axes的右上角(0.95的x坐标,horizontalalignment="right")。
  2. 获取文本框边界:调用fig.canvas.draw()确保Matplotlib渲染出文本框的实际尺寸,再通过get_window_extent()获取显示坐标下的边界,最后转换为Axes坐标。
  3. 定位左侧文本框:将左侧文本框的右对齐位置设置为右侧文本框的左边缘坐标,实现两者边缘无缝衔接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:07:52