将每个图分配给g 等变量,并使用plt.close(g.fig) 删除不需要的子图。或者遍历所有 sns.axisgrid.FacetGrid 类型变量并像这样关闭它们:
for p in plots_names:
plt.close(vars()[p].fig)
下面的完整 sn-p 就是这样做的。请注意,我正在使用 train_df = sns.load_dataset("titanic") 加载泰坦尼克号数据集。在这里,与您的示例不同,所有列名都是小写的。我还删除了 palette=col_pal 参数,因为您的 sn-p 中没有定义 col_pal。
剧情:
代码:
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [12, 8]
fig, axes = plt.subplots(nrows=3, ncols=2)
plt.tight_layout()
train_df = sns.load_dataset("titanic")
g = sns.catplot(x='pclass', y='age', data=train_df, kind='box', height=8, ax=axes[0, 0])
h = sns.catplot(x='embarked', y='age', data=train_df, kind='box', height=8, ax=axes[0, 1])
i = sns.catplot(x='sex', y='age', data=train_df, kind='box', height=8, ax=axes[1, 0])
j = sns.catplot(x='sex', y='age', hue='pclass', data=train_df, kind='box', height=8, ax=axes[1, 1])
k = sns.catplot(x='sibsp', y='age', data=train_df, kind='box', height=8, ax=axes[2, 0])
l = sns.catplot(x='parch', y='age', data=train_df, kind='box', height=8, ax=axes[2, 1])
# iterate over plots and run
# plt.close() to prevent duplicate
# subplot setup
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)]
for p in plots_names:
plt.close(vars()[p].fig)
请注意,您必须将您的图分配给变量名称才能使其工作。如果您只是将关闭图的 sn-p 添加到原始 sn-p 的末尾,则重复的子图设置将保持不变。
代码 2:
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [12, 8]
fig, axes = plt.subplots(nrows=3, ncols=2)
plt.tight_layout()
train_df = sns.load_dataset("titanic")
_ = sns.catplot(x='pclass', y='age', data=train_df, kind='box', height=8, ax=axes[0, 0])
_ = sns.catplot(x='embarked', y='age', data=train_df, kind='box', height=8, ax=axes[0, 1])
_ = sns.catplot(x='sex', y='age', data=train_df, kind='box', height=8, ax=axes[1, 0])
_ = sns.catplot(x='sex', y='age', hue='pclass', data=train_df, kind='box', height=8, ax=axes[1, 1])
_ = sns.catplot(x='sibsp', y='age', data=train_df, kind='box', height=8, ax=axes[2, 0])
_ = sns.catplot(x='parch', y='age', data=train_df, kind='box', height=8, ax=axes[2, 1])
# iterate over plots and run
# plt.close() to prevent duplicate
# subplot setup
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)]
for p in plots_names:
plt.close(vars()[p].fig)
情节 2: