首页 > 解决方案 > 获取图中的 X,Y 位置(不在图中)

问题描述

我对图中的 X 和 Y 位置有疑问。您如何看到我正在使用 gridspec 以获得更好的布局并将文本添加到图形中。问题是我试图手动获取确切的位置。这意味着我要更改 X 和 Y,fig.text(0.2, 0.5, 'matplotlib') 直到得到最终数字。

在此处输入图像描述

import matplotlib.pylab as plt
import numpy as np

vector = np.arange(0,100)
time = np.arange(0,vector.shape[0])

fig = plt.figure(figsize=(10,10))
plt.rcParams['axes.grid'] = True
gs = fig.add_gridspec(2, 2)
    
ax1 = fig.add_subplot(gs[0, :])        
ax1.plot(time,vector)  
fig.text(0.2, 0.5, 'matplotlib') 

Link我已经找到了一个交互式解决方案,但它只适用于 Plot。

有人知道如何管理这个吗?

标签: pythonmatplotlib

解决方案


您可以创建混合变换,其中 y 坐标具有图形变换。并且 x 坐标有一个轴变换。图形变换在图形的左侧/底部测量为 0,在图形的右侧/顶部测量为 1。轴变换是类似的,但关于轴。该参数clip_on=False允许在轴区域之外绘制(文本默认允许这样做)。

import matplotlib.transforms as mtransforms
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

fig, ax = plt.subplots(gridspec_kw={})

# the x coords of this transformation are axes, and the y coord are fig
trans = mtransforms.blended_transform_factory(ax.transAxes, fig.transFigure)

x, w = 1, -0.3  # axes coordinates
y, h = 0.04, 0.06  # figure coordinates
ax.text(x + w / 2, y + h / 2, 'hello', transform=trans, ha='center', va='center')
rect = mpatches.Rectangle((x, y), w, h, transform=trans, edgecolor='crimson', facecolor='yellow', clip_on=False)
ax.add_patch(rect)

fig.tight_layout(pad=2)
plt.show()

示例图

PS:您可以设置垂直对齐va='right',使文本的右边距与右轴对齐。您还可以使用transform=ax.transAxes负 y 坐标来绘制相对于轴的所有内容。


推荐阅读