如何正确显示一个图中的多个图像?

wit*_*221 66 matplotlib

我试图在一个图上显示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()
Run Code Online (Sandbox Code Playgroud)

我希望它们自然地出现在网格布局中(比如4x5),每个都有相同的大小.部分问题是我不知道add_subplot的参数是什么意思.文档声明参数是行数,列数和图号.没有定位论点.此外,图号只能是1或2.我怎样才能实现这一点?

swa*_*hai 149

以下是我可以尝试的方法:

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()
Run Code Online (Sandbox Code Playgroud)

结果图像:

output_image

(原答复日期:17年10月7日4:20)

EDIT1

由于这个答案很受欢迎,超出了我的预期.我发现需要做一些小改动才能灵活地操纵各个地块.所以我将这个新版本提供给原始代码.从本质上讲,它提供: -

  1. 访问子图的各个轴
  2. 可以在选定的轴/子图上绘制更多特征

新代码:

import numpy as np
import matplotlib.pyplot as plt

w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5

# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# ax enables access to manipulate each of subplots
ax = []

for i in range(columns*rows):
    img = np.random.randint(10, size=(h,w))
    # create subplot and append to ax
    ax.append( fig.add_subplot(rows, columns, i+1) )
    ax[-1].set_title("ax:"+str(i))  # set title
    plt.imshow(img, alpha=0.25)

# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)

plt.show()  # finally, render the plot
Run Code Online (Sandbox Code Playgroud)

由此产生的情节:

在此输入图像描述

  • 要摆脱子图周围的数字/标记,可以执行ax = fig.add_subplot(行,列,i)ax.set_xticks([])ax.set_yticks([]) (2认同)

小智 7

您可以尝试以下操作:

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()
Run Code Online (Sandbox Code Playgroud)

然而,这基本上只是从这里复制和粘贴:单个窗口中的多个数字,因此这篇文章应该被认为是重复的。

我希望这有帮助。