【发布时间】:2020-05-20 01:13:22
【问题描述】:
我创建了一堆图,并希望根据它们的特征对其中的一些进行子集化。如何遍历命名空间并列出其中的一些或全部?甚至可能使用列表推导对其中一些进行操作?我知道这可以通过数据框轻松完成,例如问题Iterating over different data frames using an iterator
的一些答案绘图的一个实际示例可能是关闭一些绘图,例如 How to stop plots printing twice in jupyter when using subplots?,您必须在其中运行 plt.close(g.fig),其中 g 是许多绘图之一,以防止重复的子绘图设置。
设置:
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])
在此示例中,如何在不明确命名每个图的情况下循环 i for [g, h, i, j] 并运行 plt.close(i.fig)?
我的尝试:
运行vars() 将返回'g', 'h', 'i', j。运行vars()['g']
会给我<seaborn.axisgrid.FacetGrid at 0x1c1bc940>。所以我认为一种选择是运行
[elem for elem in vars() if elem in 'seaborn.axisgrid.FacetGrid'] 无需使用特定名称即可访问每个图。但这将返回['g', 'i', 't', 's', 'ax'],其中缺少h 和j,尽管运行vars()['h'] 确实会返回<seaborn.axisgrid.FacetGrid at 0x1bfa74a8>。
在vars()['ax'](即<matplotlib.axes._subplots.AxesSubplot at 0x1c1bce10>)的输出中似乎没有任何seaborn.axisgrid.FacetGrid 的痕迹。 vars()['t'] 和 vars()['t'] 的输出是长浮点数组。
我想我可能以完全错误的方式处理这件事。任何其他建议都会很棒!
【问题讨论】:
标签: python