在图上创建标记的水平线

时间:2019-07-09 04:52:28

标签: matplotlib annotate horizontal-line

我正在尝试复制此图:

enter image description here

但是我在用横条创建水平线时遇到了麻烦。我已经尝试过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()

生产这种条形的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

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

enter image description here

答案 1 :(得分:0)

接受的答案非常有效,谢谢。

此外,我通过以下方式使颜色自动化:

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)