【问题标题】:How do I offset lines in matplotlib by X points如何将 matplotlib 中的线条偏移 X 点
【发布时间】:2014-05-25 23:36:02
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    以下代码符合我的要求。它使用 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()
    

    【讨论】:

      【解决方案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)。那是你想要的吗?

      【讨论】:

      • 嗨,亚历克斯,感谢您的回答。我的目标是避免使用数据坐标作为偏移量,而是以绝对单位(英寸或点)指定偏移量。这是因为轴限制容易发生变化,但这不应该改变距离标记的绘制方式。 (同样,我希望避免使用图像大小的一小部分,因为图像大小也可能发生变化。)
      猜你喜欢
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      相关资源
      最近更新 更多