`plt.imshow` 只生成子图的最后一张图片

`plt.imshow` only produces the last image of a suplot

我正在尝试将四个 DICOM 图像样本打印到我的笔记本上。

我创建了以下内容:

import os
import pydicom as dicom
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

PATH = '../data/train/'
files = os.listdir(PATH)

np.random.seed(42)
random_four = np.random.randint(0, len(files), size=4)
subplots = [[0,0],[0,1],[1,0],[1,1]]

fig, axs = plt.subplots(2,2, figsize=(8,8))

for image_number in range(4):
    sample = dicom.dcmread(PATH+files[random_four[image_number]])
    axs[subplots[image_number]] = plt.imshow(sample.pixel_array, cmap='gray')

这会产生一个子图,但实际上只有最后一张图片显示:

如何使用子图将所有这四张图像正确地打印到笔记本中?

使用Axes.imshow.

您还可以使用 zipaxs.ravel() 循环遍历子图:

fig, axs = plt.subplots(2, 2, figsize=(8,8))

for ax, image_number in zip(axs.ravel(), range(4)):
    sample = dicom.dcmread(PATH+files[random_four[image_number]])
    ax.imshow(sample.pixel_array, cmap='gray')

或使用enumerate:

for image_number, ax in enumerate(axs.ravel()):