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

如何获取AnchoredText的坐标/范围以实现ConnectionPatch动态连接?

解决Matplotlib中用ConnectionPatch连接坐标轴与AnchoredText的问题

要动态获取AnchoredText的位置来创建ConnectionPatch,核心是利用get_window_extent()方法获取其屏幕坐标范围,但必须先触发图形渲染(Matplotlib在绘制前不会计算元素的屏幕位置)。以下是具体实现步骤和代码:

关键操作

  • 先调用fig.canvas.draw()完成图形渲染,确保AnchoredText的屏幕坐标已计算。
  • 通过anchored_text.get_window_extent()获取其边界框(Bbox),从中提取需要连接的点(比如中心、边缘)。
  • 使用ConnectionPatch时,可灵活选择坐标系统(如'figure pixels'直接用屏幕坐标,或转换为目标坐标轴的分数坐标)。

完整代码示例

import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText
from matplotlib.patches import ConnectionPatch

# 创建带多个坐标轴的图形
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

# 在ax2中添加AnchoredText
anchored_text = AnchoredText("目标文本", loc='upper center', frameon=True, ax=ax2)
ax2.add_artist(anchored_text)

# 先渲染图形,才能获取AnchoredText的屏幕位置
fig.canvas.draw()

# 获取AnchoredText的边界框(屏幕坐标,单位是像素)
at_bbox = anchored_text.get_window_extent()
# 取边界框的中心作为连接点
at_center_x = at_bbox.get_points().mean(axis=0)[0]
at_center_y = at_bbox.get_points().mean(axis=0)[1]

# 创建ConnectionPatch:连接ax1的右上角到AnchoredText的中心
# 坐标系统:ax1用'axes fraction'(0-1范围),AnchoredText用'figure pixels'
conn = ConnectionPatch(
    xyA=(1, 1), coordsA=ax1.transAxes,
    xyB=(at_center_x, at_center_y), coordsB=fig.dpi_scale_trans,
    arrowstyle="->", linewidth=2, color="red"
)

# 添加ConnectionPatch到图形
fig.add_artist(conn)

# 调整子图间距
plt.subplots_adjust(wspace=0.3)
plt.show()

补充说明

  • 如果需要将AnchoredText的屏幕坐标转换为目标坐标轴的数据坐标,可使用以下代码:
    # 将屏幕坐标转换为ax2的数据坐标
    at_data_coord = ax2.transData.inverted().transform((at_center_x, at_center_y))
    
  • 不管loc参数设置的是什么位置,get_window_extent()都能正确获取AnchoredText实际渲染后的位置,完全不需要手动估算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:55:42