Matplotlib - 组合文本/注释坐标系

sta*_*ker 6 python matplotlib python-3.x

在绘图上定位文本/注释时是否可以组合两个不同的坐标系?如本问题所述,您可以将注释的位置指定为绘图大小的分形位置。文档中也对此进行了进一步介绍。

不过,我想指定分形坐标系统中注释的 x 坐标和数据坐标系统中的 y 坐标。这将允许我将注释附加到水平线,但确保注释始终靠近(远离绘图大小的一部分)绘图边缘。

C.K*_*.K. 5

使用blended_transform_factory(x_transform,y_transform)x_transform该函数返回适用于 x 轴和y_transformy 轴的新变换。例如:

import matplotlib.pyplot as plt
from matplotlib.transforms import blended_transform_factory
import numpy as np

x = np.linspace(0, 100,1000)
y = 100*np.sin(x)
text = 'Annotation'

f, ax = plt.subplots()
ax.plot(x,y)
trans = blended_transform_factory(x_transform=ax.transAxes, y_transform=ax.transData)
ax.annotate(text, xy=[0.5, 50], xycoords=trans,ha='center')
Run Code Online (Sandbox Code Playgroud)

然后将注释放在 x 轴的中心和y=50y 轴的位置。

在此输入图像描述