pyplot.text() 画错了地方

pyplot.text() draws in the wrong place

我正在使用 cifar100 数据集,我已经提取了一些我需要用于训练的 类,现在我正在尝试可视化数据集。我想在每一行的开头添加一个标签,为此我使用了 pyplot.text 。 这是我试过的:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.pyplot import text
from tensorflow.keras.datasets import cifar100, mnist

(x_train, y_train), (x_test, y_test) = cifar100.load_data()

bed_id = (y_train == 5).reshape(x_train.shape[0])
bicycle_id = (y_train == 8).reshape(x_train.shape[0])
girl_id = (y_train == 35).reshape(x_train.shape[0])
keyboard_id = (y_train == 39).reshape(x_train.shape[0])
orchid_id = (y_train == 54).reshape(x_train.shape[0])
rocket_id = (y_train == 69).reshape(x_train.shape[0])
streetcar_id = (y_train == 81).reshape(x_train.shape[0])

bed_images = x_train[bed_id]
bicycle_images = x_train[bicycle_id]
girl_images = x_train[girl_id]
keyboard_images = x_train[keyboard_id]
orchid_images = x_train[orchid_id]
rocket_images = x_train[rocket_id]
streetcar_images = x_train[streetcar_id]


for i in range(70):
    plt.subplot(7, 10, i + 1)
    offset_y = (i % 10) * 25 + 10
    offset_x = -60
    if i < 10:
        plt.imshow(bed_images[i % 10])
        text(offset_x, offset_y, "bed", fontsize=12)
    elif 10 <= i < 20:
        plt.imshow(bicycle_images[i % 10])
        text(offset_x, offset_y, "bicycle", fontsize=12)
    elif 20 <= i < 30:
        plt.imshow(girl_images[i % 10])
        text(offset_x, offset_y, "girl", fontsize=12)
    elif 30 <= i < 40:
        plt.imshow(keyboard_images[i % 10])
        text(offset_x, offset_y, "keyboard", fontsize=12)
    elif 40 <= i < 50:
        plt.imshow(orchid_images[i % 10])
        text(offset_x, offset_y, "orchid", fontsize=12)
    elif 50 <= i < 60:
        plt.imshow(rocket_images[i % 10])
        text(offset_x, offset_y, "rocket", fontsize=12)
    elif 60 <= i < 70:
        plt.imshow(streetcar_images[i % 10])
        text(offset_x, offset_y, "streetcar", fontsize=12)

plt.show()

结果:

如您所见,它利用了数据集图像。我只想在每一行前面有一个标签。

您正在为每个图像添加文本,而您只想在新行的开头添加文本。

这是实现预期结果的一种可能方法:

images = [bed_images, bicycle_images, girl_images, keyboard_images, orchid_images, rocket_images, streetcar_images]
labels = ["bed", "bicycle", "girl", "keyboard", "orchid", "rocket", "streetcar"]

offset_x = -60
offset_y = 20
fig, axes = plt.subplots(len(labels), 10)
for i in range(len(labels)):
    axes[i, 0].text(offset_x, offset_y, labels[i], fontsize=12)
    for j in range(10):
        axes[i, j].imshow(images[i][j])
        axes[i, j].axis(False)
plt.show()