matplotlib,在多个子图中添加通用的水平线在x轴上

2 投票
1 回答
1462 浏览
提问于 2025-04-18 05:01

我的计划是使用4个 GridSpec(4,1) 来创建一个4x4的子图网格。我想在每一行的4个子图的x轴上添加一条横线。我查看了matplotlib.lines.Line2D,但没搞明白怎么用。有没有什么建议?我想让图看起来更简单,不想让它看起来像16个独立的图。

下面的图片中我只展示了前两个网格,但我希望这能更好地表达我想要实现的效果。

谢谢!祝好

代码(图形部分):

#---the graph---
fig = plt.figure(facecolor='white')

gs1 = GridSpec(4,1)
gs1.update(left = 0.15, right = .3375 , wspace=0.02)

ax1 = plt.subplot(gs1[3,0])
ax2 = plt.subplot(gs1[2,0])
ax3 = plt.subplot(gs1[1,0])
ax4 = plt.subplot(gs1[0,0])



gs2 = GridSpec(4,1)
gs2.update(left = 0.3875, right = .575, wspace=.25)

ax1 = plt.subplot(gs2[3,0])
ax2 = plt.subplot(gs2[2,0])
ax3 = plt.subplot(gs2[1,0])
ax4 = plt.subplot(gs2[0,0])


show()

在这里输入图片描述

1 个回答

2

基本上,这个想法是画一条线,并让这条线超出当前的坐标轴视图。在下面的例子中,我把这条线用红色画出来,这样更容易看清楚。

另外,你的8个图可以用嵌套循环来绘制,这样可以让代码更整洁,也能更方便地实现“在子图中共用一条线”的功能:

X=[1,3,4,5]
Y=[3,4,1,3]
L=['A', 'B', 'C', 'D']
f=plt.figure(figsize=(10,16), dpi=100)
gs1 = gridspec.GridSpec(4,1)
gs1.update(left = 0.15, right = .3375 , wspace=0.02)
gs2 = gridspec.GridSpec(4,1)
gs2.update(left = 0.3875, right = .575, wspace=.25)
sp1 = [plt.subplot(gs1[i,0]) for i in range(4)]
sp2 = [plt.subplot(gs2[i,0]) for i in range(4)]
for sp in [sp1, sp2]:
    for ax in sp:
        ax.bar(range(len(L)), X, 0.35, color='r')
        ax.bar(np.arange(len(L))+0.35, Y, 0.35)
        ax.spines['right'].set_visible(False)
        ax.yaxis.set_ticks_position('left')
        ax.spines['top'].set_visible(False)
        ax.xaxis.set_ticks_position('bottom')
        if sp==sp1:
            ax.axis(list(ax.get_xlim())+list(ax.get_ylim())) #set the axis view limit
            ll=ax.plot((0,10), (0,0), '-r') #Let's plot it in red to show it better
            ll[0].set_clip_on(False) #Allow the line to extend beyond the axis view
plt.savefig('temp.png')            

enter image description here

撰写回答