python - 如何通过 X 点偏移 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 = 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 点?我希望使用绝对坐标(例如,点或英寸)而不是数据坐标,因为轴限制很容易发生变化。

谢谢!

最佳答案

下面的代码完成了我想要的。它使用 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()

关于python - 如何通过 X 点偏移 matplotlib 中的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23839468/

相关文章:

python - 如何找到各个 x 和 y 值的拟合参数

python - 如何加载旧的 pickle 文件?

python - 从 django 注册表中删除第二个密码输入

python - 如何使 Jupyter Notebook 中的内联图更大?

python - 无法向饼图添加标题(matplotlib)

python - Matplotlib 不在 virtualenv 中显示图形

python - 如何向 matplotlib.pyplot.matshow 绘图添加标签和标题

python - 使用 Python 的 matplotlib/basemap 的颜色状态

python - 如何从中心裁剪具有特定尺寸的图像?

python - 返回列表中包含的子列表,固定大小