Home > Software design >  pyplot.text() draws in the wrong place
pyplot.text() draws in the wrong place

Time:04-25

I am working with cifar100 dataset, I have extracted some classes that I need for training, now I am trying to visiulize the data set. I want to add a label in the beginning of each line, I used pyplot.text for this. This is what I tried:

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()

Result:

enter image description here

Here as you can see it draws on the dataset images. I want to just have a label in front of each line.

CodePudding user response:

You are adding a text for each image, whereas you want to add a text only at the beginning of a new row.

This is one possible way to achieve your expected result:

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()

enter image description here

  • Related