简体   繁体   中英

matplotlib, add common horizontal lines at the x axis across multiple subplots

My plan is to have 4 GridSpec(4,1) gridspecs to create a 4x4 grid of subplots. I would like to add a horizontal line across the x-axes of each row of 4 subplots. I looked at matplotlib.lines.Line2D but couldn't really figure it out. Any suggestions? I'm trying to visually simplify the picture so it does not look like 16 separate graphs.

In the picture below I only have the first 2 gridspecs up, but I hope it offers a better idea of what I am hoping to achieve.

Thanks! Cheers

Code (the graph part):

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

在此处输入图片说明

Basically the idea is to draw a line and allow the line to extend beyond the current view of axis, in this following example, I plot that line in red in order to see it better.

Also your 8 plots can be plotted in a nested loop, which will organize the code better and make this 'common line across subplot' easier to implement:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM