2014-02-26 72 views
5

我想使用gridspec在matplotlib中製作圖像網格。問題是,我似乎無法得到它擺脫行之間的填充。matplotlib中沒有填充的圖像網格

enter image description here

這裏是我的解決方案的嘗試。

import matplotlib.pyplot as plt 
from mpl_toolkits.axes_grid1 import ImageGrid 
import numpy as np 
from os import listdir 
from os import chdir 
from PIL import Image 
import matplotlib.gridspec as gridspec 

chdir('/home/matthew/Dropbox/Work/writing/'+ 
    'paper_preperation/jump_figs') 
files = listdir('/home/matthew/Dropbox/Work/writing/'+ 
    'paper_preperation/jump_figs') 

images = [Image.open(f) for f in files] 


""" 
fig = plt.figure() 

grid = ImageGrid(fig, 111, # similar to subplot(111) 
       nrows_ncols = (2, 5), # creates 2x2 grid of axes 
       axes_pad=0.1, # pad between axes in inch. 
       ) 
""" 

num_rows = 2 
num_cols = 5 

fig = plt.figure() 
gs = gridspec.GridSpec(num_rows, num_cols, wspace=0.0) 

ax = [plt.subplot(gs[i]) for i in range(num_rows*num_cols)] 
gs.update(hspace=0) 
#gs.tight_layout(fig, h_pad=0,w_pad=0) 

for i,im in enumerate(images): 
    ax[i].imshow(im) 
    ax[i].axis('off') 
    #ax_grid[i/num_cols,i-(i/num_cols)*num_cols].imshow(im) # The AxesGrid object work as a list of axes. 
    #ax_grid[i/num_cols,i-(i/num_cols)*num_cols].axis('off') 

""" 
all_axes = fig.get_axes() 
for ax in all_axes: 
    for sp in ax.spines.values(): 
     sp.set_visible(False) 
    if ax.is_first_row(): 
     ax.spines['top'].set_visible(True) 
    if ax.is_last_row(): 
     ax.spines['bottom'].set_visible(True) 
    if ax.is_first_col(): 
     ax.spines['left'].set_visible(True) 
    if ax.is_last_col(): 
     ax.spines['right'].set_visible(True) 
""" 
plt.show() 

也沒有人知道如何使每個子圖更大?

+0

['tight_layout'](http://matplotlib.org/users/tight_layout_guide.html)有幫助嗎?另見http://stackoverflow.com/q/6541123/1643946 – Bonlenfum

+4

你看到的是matplotlib定義子圖位置的方式的限制因爲'imshow'會強制每個圖形的方面是1(因此是方形) ,即使'hspace = 0,wspace = 0'時,子圖位置的定義也會導致間隙。我現在沒有時間詳細說明,但爲了解決這個問題,您實際上需要計算每個圖形大小調整事件中的「left」,「right」,「bottom」和「top」應該是什麼。或者,只需使用'imshow(...,aspect ='auto')',但是你會有非方形像素。 –

+0

太棒了!我用'fig = plt.figure(dpi = 300)'來渲染更高的分辨率。 – colllin

回答

1

對我而言,aspect="auto"subplots_adjust的組合工作。此外,我總是試圖讓子曲線成爲二次曲線。對於個人小區大小figsize可以進行調整。

fig, axes = plt.subplots(nrows=max_rows, ncols=max_cols, figsize=(20,20)) 
for idx, image in enumerate(images): 
    row = idx // max_cols 
    col = idx % max_cols 
    axes[row, col].axis("off") 
    axes[row, col].imshow(image, cmap="gray", aspect="auto") 
plt.subplots_adjust(wspace=.05, hspace=.05) 
plt.show()