2017-10-11 83 views
1

我想繪製一個子圖,其中每個子圖都包含兩個共享x軸的子圖。我試過以下代碼:共享軸循環的Python子圖

gs_top = plt.GridSpec(6, 3, hspace = 0.0001) 
gs_base = plt.GridSpec(6, 3, hspace = 0.95) 

f2 = plt.figure() 

for i in range(9): 
    up_id = [0,1,2,6,7,8,12,13,15] 
    bot_id = [3,4,5,9,10,11,15,16,17] 

    axarr2 = f2.add_subplot(gs_top[up_id[i]]) 


    axarr2.plot() 

    ax_sub = f2.add_subplot(gs_base[bot_id[i]], sharex= axarr2) 
    ax_sub.imshow() 
    axarr2.set_title('title') 
    axarr2.xaxis.set_visible(False) 

我該如何設置參數plt.GridSpec()

回答

0

我猜你想用gridspec.GridSpecFromSubplotSpec在gridspec內創建另一個gridspec。因此,假設您需要3 x 3網格,並且每個單元格應包含兩個相互垂直連接並共享其x軸的子圖。

import matplotlib.gridspec as gridspec 
import matplotlib.pyplot as plt 
import numpy as np 

fig = plt.figure() 
gs = gridspec.GridSpec(3, 3, hspace=0.6,wspace=0.3) 

for i in range(9): 
    gss = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs[i], 
              hspace=0.0) 

    ax0 = fig.add_subplot(gss[0]) 
    ax1 = fig.add_subplot(gss[1], sharex=ax0) 

    x = np.linspace(0,6*np.pi) 
    y = np.sin(x) 
    ax0.plot(x,y) 
    ax1.plot(x/2,y) 

    ax0.set_title('title {}'.format(i)) 
    ax0.tick_params(axis="x", labelbottom=0) 

plt.show() 

3 x 3 GridSpec with 2 x 1 GridSpecFromSubplotSpec