Q:

pyplot draw method for subplots

I have 10 images of the digits 0-9, each with 28x28 pixels contained in an array X of shape (28**2, 10).
I am updating X with new pixels within a loop and I would like to update my plot at each iteration.
Currently, my code will create 100 separate figures.
def plot_output(X):
    """grayscale images of the digits 0-9
    in 28x28 pixels in pyplot

    Input, X is of shape (28^2, 10)
    """
    n = X.shape[1] # number of digits
    pixels = (28,28) # pixel shape
    fig, ax = plt.subplots(1,n)

    # cycle through digits from 0-9
    # X input array is reshaped for each 10 digits
    # to a (28,28) vector to plot
    for i in range(n):
        wi=X[:,i] # w = weights for digit

        wi=wi.reshape(*pixels)
        ax[i].imshow(wi,cmap=plt.cm.gist_gray,
            interpolation='gaussian', aspect='equal')
        ax[i].axis('off')
        ax[i].set_title('{0:0d}'.format(i))

    plt.tick_params(axis='x', which='both', bottom='off',
        top='off', labelbottom='off')

    plt.show()

for i in range(100):
    X = init_pix() # anything that generates a (728, 10) array
    plot_output(X)

I have tried using plt.draw() and pt.canvas.draw() but I can't seem to implement it correctly. I have also tried plt.clf() which didn't work for me either. 
I was able to do this fine using lines and one axis using this post but I can't get it to work on subplots.

A:

By using plt.ion() you can make the plt.show() command, that is usually blocking, not block.
Then you can update the axes with imshow, and they'll appear in your figure as they're computed.
For example:
import numpy as np
import matplotlib.pyplot as plt

n=10

X = np.random.rand(28**2,n)

fig, ax = plt.subplots(1,n)

plt.ion()
plt.show()

for i in range(n):
    wi = X[:,1].reshape(28,28)
    ax[i].imshow(wi)

    #fig.canvas.draw()  # May be necessary, wasn't for me.

plt.ioff()  # Make sure to make plt.show() blocking again, otherwise it'll run
plt.show()  #   right through this and immediately close the window (if program exits)

You'll now get ugly huge empty white axes until your axes are defined, but this should get you started.

