【问题标题】:Creating labelled horizontal lines on a plot在绘图上创建带标签的水平线
【发布时间】:2019-11-18 14:18:18
【问题描述】:

我正在尝试重现此图表:

但我在创建带有条形的水平线时遇到了麻烦。我试过annotatehlines,但它们并没有达到我想要的效果。 将 matplotlib.pyplot 导入为 plt

plt.grid(which = 'both')
plt.xticks(fontsize = 16)
plt.yticks(fontsize = 16)
plt.xlim(-0.5,8)
plt.ylim(-0.5,10)
plt.xlabel('Redshift, z', fontsize = 16)
plt.hlines(8, 0, .3)
plt.annotate(r'H$\alpha$', fontsize = 16, xy = (0,8), xycoords='data', xytext=(0,8), textcoords='data',
             arrowprops=dict(arrowstyle='<|-|>', connectionstyle='arc3', color = 'k', lw=2))
fig = plt.gcf()
width, height = 15,35   #   inches
fig.set_size_inches(width, height, forward = True)
plt.show()

制作这样的条的最佳方法是什么?

【问题讨论】:

    标签: matplotlib annotate horizontal-line


    【解决方案1】:

    我会直接使用annotate,但为了更灵活,我会将水平条的绘制和相应的文本分开

    plt.figure()
    plt.grid(which = 'both')
    plt.xticks(fontsize = 16)
    plt.yticks(fontsize = 16)
    plt.xlim(-0.5,8)
    plt.ylim(-0.5,10)
    plt.xlabel('Redshift, z', fontsize = 16)
    
    bar_ys = [8,4]
    bar_xs = [[0,6],[3,5]]
    bar_texts = [r'H$\alpha$',r'H$\beta$']
    bar_color = ['k','orange']
    
    for y,xs,t,c in zip(bar_ys,bar_xs,bar_texts,bar_color):
        plt.annotate('', xy = (xs[0],y), xycoords='data', xytext=(xs[1],y),
                     arrowprops=dict(arrowstyle='|-|', color=c, lw=2, shrinkA=0, shrinkB=0))
        plt.annotate(t, xy = (xs[1],y), xycoords='data', xytext=(-5,5), textcoords='offset points',
                     fontsize = 16, va='baseline', ha='right', color=c)
    plt.show()
    

    【讨论】:

      【解决方案2】:

      接受的答案完美无缺,谢谢。

      此外,我还自动化了颜色:

      colors = iter(cm.tab10(np.linspace(0,0.8,13)))
      
      colour = 'k'
      for y,xs,t in zip(bar_ys,bar_xs,bar_texts):
          plt.annotate('', xy = (xs[0],y), xycoords='data', xytext=(xs[1],y),
                       arrowprops=dict(arrowstyle='|-|', color=colour, lw=2, shrinkA=0, shrinkB=0))
          plt.annotate(t, xy = (xs[1],y), xycoords='data', xytext=(-5,5), textcoords='offset points',
                       fontsize = 16, va='baseline', ha='right', color=colour)
          colour = next(colors)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多