如何获取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
相关产品推荐
相关产品推荐

