Skip to content
Advertisement

Why does pylab always plot to the last created figure?

I tried to create 2 figures at the same time. I thought I could plot into each figure by specifying the desired axis as shown in the code below, but all of the data goes into the last created figure (here, fig2).

import matplotlib.pylab as pl

fig1 = pl.figure(figsize=(5, 5))
gs1 = pl.GridSpec(4, 4)

fig2 = pl.figure(figsize=(5, 5))
gs2 = pl.GridSpec(4, 4)

for axis_counter in range(11):
    ax = pl.subplot(gs1[axis_counter])
    ax.plot([0, 10], [0, 10])

When I run this nothing plots in the fig1 axes, it all goes into the fig2 axes even though I’m explicitly calling gs1 here. I imagine pylab is latching onto the last created figure, but that behavior does not make sense.

Advertisement

Answer

My recommendation is to never use pylab.

If your in an interactive console session, pyplot is ok. But really, you should use the object-oriented interface. That means:

  • importing pyplot
  • create a figure either directly or with axes via (pyplot.subplots)
  • operate on those figures and axes directly.

In your case, this means:

from matplotlib import pyplot

fig1 = pyplot.figure(figsize=(5, 5))
gs1 = fig1.add_gridspec(4, 4)

fig2 = pyplot.figure(figsize=(5, 5))
gs2 = fig2.add_gridspec(3, 3)

for axis_counter in range(11):
    ax = fig1.add_subplot(gs1[axis_counter])
    ax.plot([0, 10], [0, 10])


ax = fig2.add_subplot(gs2[3])
ax.plot([0, 10], [0, 10])
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement