Search code examples
pythonmatplotlibfigure

switch between figure objects in matplotlib - change the active figure


Assume we are creating two figures that we need to fill out in a loop. Here is a toy example (which doesn't work):

import matplotlib.pyplot as plt
import numpy as np

fig,ax = plt.subplots(2,2)
fig1,ax1 = plt.subplots(2,2)

for i in np.arange(4):
    ax = plt.subplot(2, 2, i+1)
    sns.distplot(np.random.normal(0,1,[1,100]), ax=ax)
    ax1 = plt.subplot(2, 2, i+1)
    sns.distplot(np.random.normal(-1,1,[1,100]),color='r', ax=ax1)

This does not work as ax = plt.subplot(25, 4, i+1) will simply refer to the last figure created (fig1) which is currently active and ax1 = plt.subplot(25, 4, i+1) will simply create another object referring to the same position which will lead to two plots being generated on the same position.
So, how do I change the active figure?
I had a look at this question but didn't manage to make it work for my case.

Current output

The code results in an empty fig

fig

and it plots everything in fig1

fig1

Desired output

This is how it should behave:

fig

fig2

fig1

fig3


Solution

  • I would use flatten:

    import matplotlib.pyplot as plt
    import numpy as np
    import seaborn as sns
    
    fig,ax = plt.subplots(2,2)
    ax = ax.flatten()
    fig1,ax1 = plt.subplots(2,2)
    ax1 = ax1.flatten()
    
    for i in np.arange(4):
        sns.distplot(np.random.normal(0,1,[1,100]), ax=ax[i])
        sns.distplot(np.random.normal(-1,1,[1,100]),color='r', ax=ax1[i])