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!