2016-01-21 108 views
12

我试图创建一个由2x2网格组成的图形,其中每个象限中有2个垂直堆叠的子图(即2x1网格)。不过,我似乎无法弄清楚如何实现这一目标。Matplotlib - 将子图添加到子图中?

最近我得到的是使用gridspec和一些丑陋的代码(见下文),但因为gridspec.update(hspace=X)更改所有subplots的间距我仍然不是我想要的位置。

理想情况下,我想要的是,使用下面的图片作为示例,减少每个象限内的子图之间的间距,同时增加顶部和底部象限之间的垂直间距(即1-3和2-4之间)。

有没有办法做到这一点(使用或不使用gridspec)?我最初设想的是生成每个子子网格(即每个2x1网格)并将它们插入到更大的2x2网格子图中,但我还没有想出如何将子图添加到子图中,如果偶数一种方式。

enter image description here

import matplotlib.pyplot as plt 
import matplotlib.gridspec as gridspec 
plt.figure(figsize=(10, 8)) 
gs = gridspec.GridSpec(4,2) 
gs.update(hspace=0.4) 
for i in range(2): 
    for j in range(4): 
     ax = plt.subplot(gs[j,i]) 
     ax.spines['top'].set_visible(False) 
     ax.spines['right'].set_visible(False) 
     plt.tick_params(which='both', top='off', right='off') 
     if j % 2 == 0: 
      ax.set_title(str(i+j+1)) 
      ax.plot([1,2,3], [1,2,3]) 
      ax.spines['bottom'].set_visible(False) 
      ax.get_xaxis().set_visible(False) 
     else: 
      ax.plot([1,2,3], [3,2,1]) 

回答

18

你可以nest your GridSpec using SubplotSpec。外部网格将是2 x 2,内部网格将是2 x 1.下面的代码应该给你基本的想法。

import matplotlib.pyplot as plt 
import matplotlib.gridspec as gridspec 

fig = plt.figure(figsize=(10, 8)) 
outer = gridspec.GridSpec(2, 2, wspace=0.2, hspace=0.2) 

for i in range(4): 
    inner = gridspec.GridSpecFromSubplotSpec(2, 1, 
        subplot_spec=outer[i], wspace=0.1, hspace=0.1) 

    for j in range(2): 
     ax = plt.Subplot(fig, inner[j]) 
     t = ax.text(0.5,0.5, 'outer=%d, inner=%d' % (i,j)) 
     t.set_ha('center') 
     ax.set_xticks([]) 
     ax.set_yticks([]) 
     fig.add_subplot(ax) 

fig.show() 

enter image description here

+0

完美,谢谢:) – user3014097