2017-10-07 54 views
1

我试图在一个图上显示20个随机图像。图像确实显示,但它们被覆盖。我使用:如何正确显示一幅图中的多个图像?

import numpy as np 
import matplotlib.pyplot as plt 
w=10 
h=10 
fig=plt.figure() 
for i in range(1,20): 
    img = np.random.randint(10, size=(h,w)) 
    fig.add_subplot(i,2,1) 
    plt.imshow(img) 
plt.show() 

我想他们在网格布局中自然会出现(4x5的说),每个具有相同的尺寸。部分问题是我不知道add_subplot的含义是什么意思。该文档指出参数是行数,列数和绘图编号。没有定位参数。此外,绘图编号只能是1或2.我该如何实现?

回答

8

这里是我的方法,你可以尝试:

import numpy as np 
import matplotlib.pyplot as plt 

w=10 
h=10 
fig=plt.figure(figsize=(8, 8)) 
columns = 4 
rows = 5 
for i in range(1, columns*rows +1): 
    img = np.random.randint(10, size=(h,w)) 
    fig.add_subplot(rows, columns, i) 
    plt.imshow(img) 
plt.show() 

产生的图像:

output_image

1

你可以尝试以下方法:

import matplotlib.pyplot as plt 
import numpy as np 

def plot_figures(figures, nrows = 1, ncols=1): 
    """Plot a dictionary of figures. 

    Parameters 
    ---------- 
    figures : <title, figure> dictionary 
    ncols : number of columns of subplots wanted in the display 
    nrows : number of rows of subplots wanted in the figure 
    """ 

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows) 
    for ind,title in zip(range(len(figures)), figures): 
     axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet()) 
     axeslist.ravel()[ind].set_title(title) 
     axeslist.ravel()[ind].set_axis_off() 
    plt.tight_layout() # optional 



# generation of a dictionary of (title, images) 
number_of_im = 20 
w=10 
h=10 
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)} 

# plot of the images in a figure, with 5 rows and 4 columns 
plot_figures(figures, 5, 4) 

plt.show() 

然而,这基本上只是复制并粘贴到这里:Multiple figures in a single window由于这个原因,这篇文章应该被认为是重复的。

我希望这会有所帮助。