我使用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()
有没有办法让ax.annotate()
绘制的线被X点偏移?我希望使用绝对坐标(例如,点或英寸)而不是数据坐标,因为轴限制很容易发生变化。
谢谢!
答案 0 :(得分:3)
以下代码可以满足我的需求。它使用ax.transData和figure.get_dpi():
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()
答案 1 :(得分:2)
您的预期产量是多少?如果您只是想要移动箭头,而是垂直绘制,那么annotate
的API就是
annotate(s, xy, xytext=None, ...)
所以你可以画出像
这样的东西ax.annotate("", (0,0.01), (1,0.01),
size = 10,
arrowprops = dict(arrowstyle = '<|-|>'))
在y方向的数据坐标中向上移动0.01
。您还可以在annotate
中将坐标指定为总数字大小的一部分(请参阅doc)。那是你想要的吗?