2017-03-17 133 views
2

我正在嘗試創建一個連接子圖(放置gridspec,每個子圖都是8x8像素)的4x4網格的好圖。我不斷努力爭取地塊之間的間隔,以配合我試圖告訴它做的事情。我想象這個問題是由於在圖的右側繪製顏色條並調整圖中的圖的位置以適應的。但是,即使沒有包含彩條,這個問題似乎也會出現,這讓我更加困惑。它也可能與邊距有關。下面顯示的圖像由相關代碼生成。正如你所看到的,我試圖讓這些圖之間的空間變爲零,但似乎並不奏效。任何人都可以建議嗎?消除matplotlib中子圖之間的空白

fig = plt.figure('W Heat Map', (18., 15.)) 
gs = gridspec.GridSpec(4,4) 
gs.update(wspace=0., hspace=0.) 
for index in indices: 
    loc = (i,j) #determined by the code 
    ax = plt.subplot(gs[loc]) 
    c = ax.pcolor(physHeatArr[index,:,:], vmin=0, vmax=1500) 
    # take off axes 
    ax.axis('off') 
    ax.set_aspect('equal') 
fig.subplots_adjust(right=0.8,top=0.9,bottom=0.1) 
cbar_ax = heatFig.add_axes([0.85, 0.15, 0.05, 0.7]) 
cbar = heatFig.colorbar(c, cax=cbar_ax) 
cbar_ax.tick_params(labelsize=16) 
fig.savefig("heatMap.jpg") 

Rectangle figure

類似地,在製備方形花紋無彩條:

fig = plt.figure('W Heat Map', (15., 15.)) 
gs = gridspec.GridSpec(4,4) 
gs.update(wspace=0., hspace=0.) 
for index in indices: 
    loc = (i,j) #determined by the code 
    ax = plt.subplot(gs[loc]) 
    c = ax.pcolor(physHeatArr[index,:,:], vmin=0, vmax=400, cmap=plt.get_cmap("Reds_r")) 
    # take off axes 
    ax.axis('off') 
    ax.set_aspect('equal') 
fig.savefig("heatMap.jpg") 

Square figure

回答

3

當軸縱橫比被設定爲不自動調節(例如,使用set_aspect("equal")或數字方面,或者通常使用imshow),則可能在su即使wspacehspace設置爲0。爲了消除數字之間的空白,你可以看看下面的問題

  1. How to remove gaps between *images* in matplotlib?
  2. How to combine gridspec with plt.subplots() to eliminate space between rows of subplots
  3. How to remove the space between subplots in matplotlib.pyplot?

您可能首先考慮this answer第一個問題,在那裏解決辦法是用從單個陣列中構建一個單個陣列,然後使用pcolor,來繪製這個單個陣列或imshow。這使得以後添加一個顏色條變得特別舒服。

否則,請考慮設置圖形參數和子圖參數,使得不留下whitespae。第二個問題的計算公式在this answer

的改編版本,彩條是這樣的:

import matplotlib.pyplot as plt 
import matplotlib.colors 
import matplotlib.cm 
import numpy as np 

image = np.random.rand(16,8,8) 
aspect = 1. 
n = 4 # number of rows 
m = 4 # numberof columns 
bottom = 0.1; left=0.05 
top=1.-bottom; right = 1.-0.18 
fisasp = (1-bottom-(1-top))/float(1-left-(1-right)) 
#widthspace, relative to subplot size 
wspace=0 # set to zero for no spacing 
hspace=wspace/float(aspect) 
#fix the figure height 
figheight= 4 # inch 
figwidth = (m + (m-1)*wspace)/float((n+(n-1)*hspace)*aspect)*figheight*fisasp 

fig, axes = plt.subplots(nrows=n, ncols=m, figsize=(figwidth, figheight)) 
plt.subplots_adjust(top=top, bottom=bottom, left=left, right=right, 
        wspace=wspace, hspace=hspace) 
#use a normalization to make sure the colormapping is the same for all subplots 
norm=matplotlib.colors.Normalize(vmin=0, vmax=1) 
for i, ax in enumerate(axes.flatten()): 
    ax.imshow(image[i, :,:], cmap = "RdBu", norm=norm) 
    ax.axis('off') 
# use a scalarmappable derived from the norm instance to create colorbar 
sm = matplotlib.cm.ScalarMappable(cmap="RdBu", norm=norm) 
sm.set_array([]) 
cax = fig.add_axes([right+0.035, bottom, 0.035, top-bottom]) 
fig.colorbar(sm, cax=cax) 

plt.show() 

enter image description here

相關問題