1

I've created a bunch of plots and would like to subset a few of them by their characteristics. How can I loop through the namespace and make a list of some or all of them? And maybe even do operations on some of them using list comprehensions? I know this can be easily done with dataframes like in some of the answers to the question Iterating over different data frames using an iterator

A practical example for plots could be to close some plots like in How to stop plots printing twice in jupyter when using subplots? where you have to run plt.close(g.fig) where g is one of many plots in order to prevent a duplicate subplot setup.

Setup:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = [12, 8]
df = sns.load_dataset("exercise")

f, axes = plt.subplots(2, 2)

g=sns.catplot(x="time", y="pulse", hue="kind", data=df, ax=axes[0, 0])
h=sns.catplot(x="time", y="pulse", hue="kind", data=df, ax=axes[0, 1])
i=sns.catplot(x="time", y="pulse", hue="kind", data=df, ax=axes[1, 0])
j=sns.catplot(x="time", y="pulse", hue="kind", data=df, ax=axes[1, 1])

In this example, how can I loop over i for [g, h, i, j] and run plt.close(i.fig) without explicitly naming each plot?

What I've tried:

Running vars() will return, among other things, 'g', 'h', 'i', j. And running vars()['g'] will give me <seaborn.axisgrid.FacetGrid at 0x1c1bc940>. So i thought one option to would be to run [elem for elem in vars() if elem in 'seaborn.axisgrid.FacetGrid'] to access each plot without using the specific names. But this will return ['g', 'i', 't', 's', 'ax'], where h and j are missing although running vars()['h'] will indeed return <seaborn.axisgrid.FacetGrid at 0x1bfa74a8>.

And there does not seem to be any trace of seaborn.axisgrid.FacetGrid in the output from vars()['ax'] which is <matplotlib.axes._subplots.AxesSubplot at 0x1c1bce10>. And the output for vars()['t'] and vars()['t'] are long arrays of floats.

I guess I may be approaching this thing in a completely wrong way. Any other suggestions would be great!

vestland
  • 55,229
  • 37
  • 187
  • 305

1 Answers1

1

So just to be clear, I am not in any manner familiar with how seaborn works. What I was able to do with your setup code was the following -

var_dict = vars().copy()
var_keys = var_dict.keys()

plots_names = [x for x in var_keys if isinstance(var_dict[x], sns.axisgrid.FacetGrid)]
print(plots_names )

I had to make a copy of vars() since it changes as you iterate over it. Using the builtin function isinstance() I looked for all instances of seaborn.axisgrid.FacetGrid in the copy of vars() and returned all the keys that matched in a list. This is the output -

['g', 'h', 'i', 'j']
Karan Shishoo
  • 2,402
  • 2
  • 17
  • 32