在绘图上创建带标签的水平线

Creating labelled horizontal lines on a plot

我正在尝试重现此图:

但是我在创建带有条形的水平线时遇到了问题。我试过 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()

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

我会直接使用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()

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

此外,我将颜色自动化:

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)