python - 如何在一张图中显示多张图片

标签 python matplotlib imshow

我正在尝试在单个图形上显示 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 的参数是什么意思。文档指出参数是行数、列数和绘图号。没有定位争论。另外,地 block 编号只能是 1 或 2。我该如何实现这一点?

最佳答案

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

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

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

编辑 1

因为这个答案的受欢迎程度超出了我的预期。我发现需要进行一些小的更改才能灵活地操纵各个图。所以我将这个新版本提供给原始代码。 本质上,它提供了:-

  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

结果图:

enter image description here

编辑2

在前面的示例中,代码提供了对具有单个索引的子图的访问,当图形具有许多行/列的子图时,这很不方便。这是它的替代方案。下面的代码提供了使用[row_index][column_index]对子图的访问,这更适合操作许多子图的数组。

import matplotlib.pyplot as plt
import numpy as np

# settings
h, w = 10, 10        # for raster image
nrows, ncols = 5, 4  # array of sub-plots
figsize = [6, 8]     # figure size, inches

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

# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)

# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
    # i runs from 0 to (nrows*ncols-1)
    # axi is equivalent with ax[rowid][colid]
    img = np.random.randint(10, size=(h,w))
    axi.imshow(img, alpha=0.25)
    # get indices of row/column
    rowid = i // ncols
    colid = i % ncols
    # write row/col indices as axes' title for identification
    axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))

# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)

plt.tight_layout(True)
plt.show()

结果图:

plot3

子图数组的刻度和刻度标签

如果所有子图共享相同的值范围,则可以隐藏子图附带的一些刻度和刻度标签,以获得更清晰的图。除了左侧和底部的外边缘(如下图所示)之外,所有刻度和刻度标签都可以隐藏。

share_ticklabels

要实现左侧和底部边缘仅具有共享刻度标签的绘图,您可以执行以下操作:-

Add options sharex=True, sharey=True in fig, ax = plt.subplots()

该行代码将变为:

fig,ax=plt.subplots(nrows=nrows,ncols=ncols,figsize=figsize,sharex=True,sharey=True)

指定所需的刻度数和要绘制的标签,

inside the body of for i, axi in enumerate(ax.flat):, add these code

axi.xaxis.set_major_locator(plt.MaxNLocator(5))
axi.yaxis.set_major_locator(plt.MaxNLocator(4))

数字 5 和 4 是要绘制的刻度/刻度标签的数量。您可能需要适合您的绘图的其他值。

关于python - 如何在一张图中显示多张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46615554/

相关文章:

python - Windows 上的 pip 给出错误 - 未知或不受支持的命令 'install'

python-3.x - opencv python3 中 imshow 的段错误

python-3.x - 如何使用 matplotlib 绘制半圆

python - 如何在matplotlib中绘制从训练集的每个点到曲面的垂直线

python - 从 x、y、z 值绘制的 matplotlib 2D 图

具有特定值颜色图的 Python imshow

python - 构建 python .whl 时排除目录?

python - 如何重载除法并与Python 2.x中的__future__除法兼容

python - 尝试使用Python在Socket中扫描IP以获取域名

python - 省略 matplotlib 图中的连接线,例如y = tan(x)