python - 获取图中的 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。
有人知道如何管理这个吗?
解决方案
您可以创建混合变换,其中 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 坐标来绘制相对于轴的所有内容。
推荐阅读
- java - Spring Webflux Webclient | 内容类型标题设置问题
- python - sum 内的积分给出索引标签错误
- openvino - 我试图在线关注 Openvino 教程,但我被困在找不到 cmakelist
- android - 文件选择器打开“最近”文件夹而不是插入的路径
- php - Laravel备份错误将大型备份上传到s3
- css - 如何创建具有背景艺术的 ui 组件。给出的例子
- javascript - 是否可以在函数内重新定义函数中的参数?
- r - 如何在 R 中将相关词与文本挖掘捆绑在一起
- php - “woocommerce_login_redirect”过滤器挂钩的问题
- amazon-web-services - AWS EC2如何在没有密钥的情况下连接?