1

我正在尝试重现此图:

在此处输入图像描述

但我无法用条形创建水平线。我试过了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()

生产这样的酒吧的最佳方法是什么?

4

2 回答 2

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()

在此处输入图像描述

于 2019-07-09T05:11:48.393 回答
1

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

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

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)
于 2019-07-09T07:58:30.873 回答