2017-08-30 91 views
0

我想向特定的matplotlib圖中添加不同大小的子圖,但我不確定如何這樣做。使用「subplot2grid」方法將子圖添加到特定圖形

import matplotlib.pyplot as plt 

fig = plt.figure() 

ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2) 
ax1 = plt.subplot2grid((2, 2), (1, 1)) 

plt.show() 

上面的代碼建立一個數字,並增加了兩個副區到該圖中,每個具有不同尺寸的:在有隻存在一個圖中,「subplot2grid」的情況下可以如下利用。現在,我的問題出現在有多個數字的情況下 - 我找不到使用「subplot2grid」將子圖添加到特定圖的適當方式。使用更簡單的「add_subplot」的方法,可以添加次要情節到特定的數字,如在下面的代碼看出:

import matplotlib.pyplot as plt 

fig1 = plt.figure() 
fig2 = plt.figure() 

ax1 = fig1.add_subplot(2, 2, 1) 
ax2 = fig1.add_subplot(2, 2, 4) 

plt.show() 

我尋找類似方法,用於將不同尺寸的副區(優選使用某種的網格管理器,例如「subplot2grid」)到特定的圖形。我對使用plt。「x」樣式有所保留,因爲它在創建的最後一個數字上運行 - 我的代碼將有幾個數字,所有這些數字都需要具有不同大小的子圖。

由於提前,

柯蒂斯M.

+1

您可以設置目前的數字,那麼你的plt。「x」風格的命令會轉到你選擇的任何一個數字。 https://stackoverflow.com/questions/7986567/matplotlib-how-to-set-the-current-figure#7987462 – RuthC

回答

1

未來(可能是即將發佈?),subplot2grid 將採取fig參數

subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs) 

使得下列會可能的:

import matplotlib.pyplot as plt 

fig1=plt.figure() 
fig2=plt.figure() 

ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2, fig=fig1) 
ax2 = plt.subplot2grid((2, 2), (1, 1), fig=fig1) 

plt.show() 

截至目前(版本2.0.2),這還不可能。另外,您也可以手動定義底層GridSpec

import matplotlib.pyplot as plt 
from matplotlib.gridspec import GridSpec 

fig1=plt.figure() 
fig2=plt.figure() 

spec1 = GridSpec(2, 2).new_subplotspec((0,0), colspan=2) 
ax1 = fig1.add_subplot(spec1) 
spec2 = GridSpec(2, 2).new_subplotspec((1,1)) 
ax2 = fig1.add_subplot(spec2) 

plt.show() 

或者你可以簡單的設置目前的數字,這樣plt.subplot2grid將上精確的數字工作(如圖this question

import matplotlib.pyplot as plt 

fig1=plt.figure(1) 
fig2=plt.figure(2) 

# ... some other stuff 

plt.figure(1) # set current figure to fig1 
ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2) 
ax2 = plt.subplot2grid((2, 2), (1, 1)) 

plt.show() 
+0

GridSpec的手動定義工作得很好。謝謝! –