Search code examples
matplotlibipythonsparse-matrix

Showing several sparse matrix plots with IPython and matplotlib


I'm using IPython and matplotlib to show sparce matricies, like this:

%matplotlib inline
import math

a = [ [randint(2) for j in range(0,5)] for i in range(0, 5)]
spy(a)

matplotlib output

Is it possible to call spy in a loop, to show several plots? This code only shows one, but I'd like it to show all five.

plots = [ [ [randint(2) for j in range(0,5)] for i in range(0, 5)] for x in range(0,5)]

for plot in plots:
    spy(plot)

Solution

  • You can call it in a loop, but first let's make five random 5x5 sparse arrays:

    ms = np.random.randint(0, 2, (5, 5, 5))
    

    If you want them to show up as separate figures, you must create a new figure each time:

    for m in ms:
        plt.figure()
        plt.spy(m)
    

    Or, you can make 1 figure with 5 subplots:

    f, axes = plt.subplots(1, 5)  # 1 row, 5 columns
    for ax, m in zip(axes, ms):
        ax.spy(m)