Python 如何将matplotlib中的线偏移X点

Python 如何将matplotlib中的线偏移X点,python,matplotlib,Python,Matplotlib,我正在使用matplotlib绘制一些我希望用箭头(距离标记)注释的数据。这些箭头应偏移多个点,以免与打印数据重叠: import matplotlib.pyplot as plt import matplotlib.transforms as transforms fig, ax = plt.subplots() x = [0, 1] y = [0, 0] # Plot horizontal line ax.plot(x, y) dy = 5/72 offset = transfor

我正在使用matplotlib绘制一些我希望用箭头(距离标记)注释的数据。这些箭头应偏移多个点,以免与打印数据重叠:

import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

fig, ax = plt.subplots()

x = [0, 1]
y = [0, 0]

# Plot horizontal line
ax.plot(x, y)

dy = 5/72

offset = transforms.ScaledTranslation(0, dy, ax.get_figure().dpi_scale_trans)
verttrans = ax.transData+offset

# Plot horizontal line 5 points above (works!)
ax.plot(x, y, transform = verttrans)

# Draw arrow 5 points above line (doesn't work--not vertically translated)
ax.annotate("", (0,0), (1,0),
            size = 10,
            transform=verttrans,
            arrowprops = dict(arrowstyle = '<|-|>'))

plt.show()
导入matplotlib.pyplot作为plt
将matplotlib.transforms作为转换导入
图,ax=plt.子批次()
x=[0,1]
y=[0,0]
#绘制水平线
轴图(x,y)
dy=5/72
offset=transforms.ScaledTranslation(0,dy,ax.get\u figure().dpi\u scale\u trans)
垂直传输=最大传输数据+偏移量
#在上面5点处绘制水平线(工程!)
ax.绘图(x,y,变换=垂直变换)
#在直线上方绘制箭头5点(不起作用--未垂直平移)
ax.注释(“,(0,0),(1,0),
尺寸=10,
变换=垂直变换,
arrowprops=dict(arrowstyle='')
plt.show()
有没有办法使
ax.annotate()
绘制的直线偏移X点?我希望使用绝对坐标(例如,点或英寸)而不是数据坐标,因为轴限制容易改变


谢谢

您的预期输出是什么?如果您只是想垂直移动正在绘制的箭头,则
annotate
的API是

annotate(s, xy, xytext=None, ...)
所以你可以画一些像

ax.annotate("", (0,0.01), (1,0.01),
    size = 10,
    arrowprops = dict(arrowstyle = '<|-|>'))
ax.注释(“,(0,0.01),(1,0.01),
尺寸=10,
arrowprops=dict(arrowstyle='')

在y方向的数据坐标中上移
0.01
。您还可以在
注释中指定坐标作为总地物尺寸的一部分(请参见)。这就是你想要的吗

下面的代码符合我的要求。它使用ax.transData和figure.get_dpi():

导入matplotlib.pyplot作为plt
将matplotlib.transforms作为转换导入
图,ax=plt.子批次()
x=[0,1]
y=[0,0]
轴图(x,y)
dy=5/72
对于dx,i=1#0
tmp=ax.transData.transform([(0,0)、(1,1)])
tmp=tmp[1,i]-tmp[0,i]#显示坐标中的1个单元
显示坐标中的tmp=1/tmp#1像素
tmp=tmp*dy*ax.get_figure().get_dpi()#在显示坐标中移动像素
轴图(x,y)
ax.注释(“,[0,tmp],[1,tmp],
尺寸=10,
arrowprops=dict(arrowstyle='')
plt.show()

你好,亚历克斯,谢谢你的回答。我的目标是避免对偏移使用数据坐标,而是以绝对单位(英寸或点)指定偏移。这是因为轴限制易于更改,但这不应更改距离标记的打印方式。(同样,我希望避免使用图像大小的一小部分,因为图像大小可能也会改变。)
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

fig, ax = plt.subplots()


x = [0, 1]
y = [0, 0]


ax.plot(x, y)


dy = 5/72

i = 1  # 0 for dx

tmp = ax.transData.transform([(0,0), (1,1)])
tmp = tmp[1,i] - tmp[0,i]  # 1 unit in display coords
tmp = 1/tmp  # 1 pixel in display coords
tmp = tmp*dy*ax.get_figure().get_dpi()  # shift pixels in display coords

ax.plot(x, y)

ax.annotate("", [0,tmp], [1,tmp],
            size = 10,
            arrowprops = dict(arrowstyle = '<|-|>'))

plt.show()