Pyplot animation with subplot returnn a blank canvas

Viewed 50

I was trying to animate 25 images randomly from Fashion MNIST dataset.

However as I was trying to do that, my code only returns a blank canvas.

import tensorflow as tf
from matplotlib.animation import FuncAnimation
from matplotlib import pyplot as plt
import numpy as np

# these code are from the first TensorFlow official tutorial.
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images,
                               test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# create a 10-inch canvas
fig = plt.figure(figsize=(10, 10))

def draw25Random():
    # show 25 random images from the 60k training set
    ris = np.random.randint(60000, size=25)
    ris.sort()
    for i in range(25):
        ri = ris[i]
        plt.subplot(5, 5, i+1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(train_images[ri], cmap=plt.cm.binary)
        plt.xlabel(f'{ri} // {class_names[train_labels[ri]]}')

anim = FuncAnimation(fig,
                     draw25Random,
                     interval=1000)

(the rendering 25 images part is fine and good)

Any ideas?

1 Answers

For the way matplotlib.animation.FuncAnimation works, you need to pass to it an argument i, which is a counter that increases by 1 for each frame. So you don't need to loop for i in range(25) within draw25Random function:

def draw25Random(i):
    # show 25 random images from the 60k training set
    ri = ris[i]
    plt.subplot(5, 5, i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[ri], cmap=plt.cm.binary)
    plt.xlabel(f'{ri} // {class_names[train_labels[ri]]}')

Complete code

import tensorflow as tf
from matplotlib.animation import FuncAnimation
from matplotlib import pyplot as plt
import numpy as np

# these code are from the first TensorFlow official tutorial.
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images,
                               test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

ris = np.random.randint(60000, size = 25)
ris.sort()

# create a 10-inch canvas
fig = plt.figure(figsize=(10, 10))

def draw25Random(i):
    # show 25 random images from the 60k training set
    ri = ris[i]
    plt.subplot(5, 5, i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[ri], cmap=plt.cm.binary)
    plt.xlabel(f'{ri} // {class_names[train_labels[ri]]}')

anim = FuncAnimation(fig,
                     draw25Random,
                     interval=100,
                     frames = 25)

plt.show()

enter image description here

Related