2017-03-31 45 views
1

我正在嘗試創建一個類似於 this question的圖。使用gridspec添加數字

爲什麼我只獲得兩個pannels,即只是GS2:

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

def main(): 
    fig = plt.figure() 
    gs1 = gridspec.GridSpec(1,4) 
    gs2 = gridspec.GridSpec(2,4) 

    for n in range(4): 
     ax00 = plt.subplot(gs1[0,n]) 
     ax10 = plt.subplot(gs2[0,n]) 
     ax11 = plt.subplot(gs2[1,n]) 

     ax00.plot([0,0],[0,1*n],color='r') 
     ax10.plot([0,1],[0,2*n],color='b') 
     ax11.plot([0,1],[0,3*n],color='g') 
    plt.show() 

main() 

,給了我這樣的:

enter image description here

最後,我想有一個像圖:

enter image description here

其中I使用問題末尾的代碼獲得。然而,我想要有可動性的地塊,其中gs2.update(hspace=0)給出(之所以我嘗試使用gridspec)。即我想刪除最後一行和第二行之間的空格。

def whatIwant(): 
    f, axarr = plt.subplots(3,4) 

    for i in range(4): 
     axarr[0][i].plot([0,0],[0,1*i],color='r') 
     axarr[1][i].plot([0,1],[0,2*i],color='b') #remove the space between those and be able to move the plots where I want 
     axarr[2][i].plot([0,1],[0,3*i],color='g') 
    plt.show() 
+0

Hello ImportanceOfBeingErnest,我更新了問題。對不起,我一如既往地有點簡約。現在更清楚了嗎? – Sebastiano1991

回答

1

這確實是其中一種情況,它使用GridSpecFromSubplotSpec是有意義的。也就是說,您可以創建一個總計爲GridSpec的列和2行(以及1到2的高度比)。在第一行中,您將GridSpecFromSubplotSpec設置爲一行四列。在第二行中,您將放置一行兩列和四列,另外指定一個hspace=0.0,這樣兩個底行之間沒有任何間距。

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


fig = plt.figure() 

gs = gridspec.GridSpec(2, 1, height_ratios=[1,2]) 
gs0 = gridspec.GridSpecFromSubplotSpec(1, 4, subplot_spec=gs[0], wspace=0.4) 
gs1 = gridspec.GridSpecFromSubplotSpec(2, 4, subplot_spec=gs[1], hspace=0.0, wspace=0.4) 

for n in range(4): 
    ax00 = plt.subplot(gs0[0,n]) 
    ax10 = plt.subplot(gs1[0,n]) 
    ax11 = plt.subplot(gs1[1,n], sharex=ax10) 
    plt.setp(ax10.get_xticklabels(), visible=False) 
    ax00.plot([0,0],[0,1*n],color='r') 
    ax10.plot([0,1],[0,2*n],color='b') 
    ax11.plot([0,1],[0,3*n],color='g') 
plt.show() 

enter image description here

,而不是一個在鏈接的問題的回答這個方案的好處是,你不重疊GridSpecs,因此不需要考慮他們如何相互關聯的。


如果你在爲什麼從問題的代碼沒有工作仍然有興趣:
您需要使用兩個不同的GridSpecs的每一個具有(在這種情況下3)行的總金額;但只填充第一個GridSpec的第一行和第二個GridSpec的第二行:

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

def main(): 
    fig = plt.figure() 
    gs1 = gridspec.GridSpec(3,4) 
    gs2 = gridspec.GridSpec(3,4, hspace=0.0) 

    for n in range(4): 
     ax00 = plt.subplot(gs1[0,n]) 
     ax10 = plt.subplot(gs2[1,n]) 
     ax11 = plt.subplot(gs2[2,n]) 

     ax00.plot([0,0],[0,1*n],color='r') 
     ax10.plot([0,1],[0,2*n],color='b') 
     ax11.plot([0,1],[0,3*n],color='g') 
    plt.show() 

main()