代码之家  ›  专栏  ›  技术社区  ›  Jim421616

在matplotlib中绘制垂直双头箭头

  •  1
  • Jim421616  · 技术社区  · 6 年前

    我有下面的图,显示一个线性关系(黑色)和它的残差(蓝色)。红色虚线表示残差的上下限,垂直红线表示范围:

    enter image description here

    下面是我如何编码残差的界限:

    plt.hlines(y = max(model.resid), xmin = min(x), xmax = max(x),
                   color = 'r', linestyle = 'dotted')
    plt.hlines(y = min(model.resid), xmin = min(x), xmax = max(x),
                   color = 'r', linestyle = 'dotted')
    plt.vlines(label = 'Range of residuals: %g'%(max(model.resid) - min(model.resid)),
                   x = min(x), ymin = min(model.resid), ymax = max(model.resid),
                   color = 'r', linestyle = 'solid')
    

    arrowprops = {'arrowstyle': '<->'} 之后 linestyle ,但我得到了 AttributeError: Unknown property arrowprops .

    我发现的所有问题和示例都展示了如何制作任意位置的箭头,但没有一个给出了一个很匀称的头部。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Sheldore    6 年前

    这是解决你问题的最简单的方法。这里的主要关键字是 arrowstyle="<->" . 我个人更喜欢用 plt.text 单独放置文本,使其独立于绘图中的箭头端点。它给你更多的自由。由于缺少你的数据,我不得不生成随机数据,但我保留了 x y 范围与您的相似。您可以相应地调整代码。你的问题是 arrowprops 它是 annotate vlines .

    import numpy as np
    import matplotlib.pyplot as plt
    fig = plt.figure(figsize=(8, 5))
    ax = fig.add_subplot(111)
    
    x = np.linspace(-0.4, 0.6, 1000)
    y = np.random.normal(0, 0.033, 1000)
    
    plt.plot(x, y, 'o')
    plt.hlines(y = max(y), xmin = min(x), xmax = max(x),
                   color = 'r', linestyle = 'dotted')
    plt.hlines(y = min(y), xmin = min(x), xmax = max(x),
                   color = 'r', linestyle = 'dotted')
    
    ax.annotate("",
                xy=(min(x), min(y)), xycoords='data',
                xytext=(min(x), max(y)), textcoords='data',
                arrowprops=dict(arrowstyle="<->",
                                connectionstyle="arc3", color='r', lw=2),
                )
    
    plt.text(1.2*min(x), max(y), 'Range of residuals: %g'%(max(y) - min(y)), 
             rotation = 90, fontsize = 16)
    plt.xlim(1.3*min(x), 1.3*max(x))
    

    输出

    enter image description here