2

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

CAPSLOCK
  • 6,243
  • 3
  • 33
  • 56
  • 1
    `ax` and `ax1` are your array of axes for each figure. Use `i` to index these arrays in `displot`. i.e. `sns.distplot(np.random.normal(0,1,[1,100]), ax=ax.flat[i])` and remove `ax = plt.subplot` – DavidG Apr 03 '19 at 12:32
  • @DavidG this solve my problem (perfectly) but still leaves me wonder if there is a way to switch the active figure after I created the objects with `fig,ax = plt.subplots(2,2)`,`fig1,ax1 = plt.subplots(2,2)`. – CAPSLOCK Apr 03 '19 at 12:40
  • 1
    [This may answer your second question](https://stackoverflow.com/questions/7986567/matplotlib-how-to-set-the-current-figure) – FChm Apr 03 '19 at 12:45

2 Answers2

3

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])
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
1

Couple of pointers:

  1. You are already defining a 2x2 array of axes in ax and ax1 respectively. You dont need to make subplots again inside the loop.

  2. You can simply flatten the 2X2 array and iterate over it as an array.

  3. You can add the respective axes (ax or ax1) after flattening them to the sns.distplot as axis (ax = flat_ax[i] OR ax = flat_ax1[i])

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

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

#Flatten the n-dim array of ax and ax1
flat_ax = np.ravel(ax)
flat_ax1 = np.ravel(ax1)

#Iterate over them
for i in np.arange(4):
    sns.distplot(np.random.normal(0,1,[1,100]), ax=flat_ax[i])
    sns.distplot(np.random.normal(-1,1,[1,100]),color='r', ax=flat_ax1[i])
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51