matplotlib,在x轴上跨多个子图添加公共水平线

2024-06-03 03:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我的计划是使用4GridSpec(4,1)网格规范来创建一个4x4子空间网格。我想在每行4个子图的x轴上添加一条水平线。我看着matplotlib.lines.Line2D但没能真正弄明白。有什么建议吗?我试图在视觉上简化图片,这样它看起来不像16个单独的图形。在

在下面的图片中,我只有前2个网格规格,但我希望它提供了一个更好的想法,我希望实现。在

谢谢!干杯

代码(图形部分):

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

enter image description here


Tags: right图形网格图片updatepltleftgs1
1条回答
网友
1楼 · 发布于 2024-06-03 03:16:18

基本上,我们的想法是画一条线,让这条线延伸到轴的当前视图之外,在下面的例子中,我用红色绘制这条线,以便更好地看到它。在

另外,您的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

相关问题 更多 >