是否可以在 Seaborn Facetgrid 中截断空网格?

Is It Possible to Truncate Empty Grids in Seaborn Facetgrid?

我正在 Jupyter 笔记本中编写代码,并且有一个 Seaborn facetgrid,我希望它有 4 列和 3 行。每个地块代表 10 个国家/地区列表中的一个不同国家/地区。由于总共有 12 个网格,而最后两个是空的,有没有办法摆脱最后两个网格?使尺寸为 5 x 2 的解决方案不是一个选项,因为当如此多的图被挤压在一起时很难看到。

代码:

ucb_w_reindex_age = ucb_w_reindex[np.isfinite(ucb_w_reindex['age'])]
ucb_w_reindex_age = ucb_w_reindex_age.loc[ucb_w_reindex_age['age'] < 120]

def ageSeries(country):
    return ucb_w_reindex_age.loc[ucb_w_reindex_age['country_destination'] == country].age.fillna(value=30).resample('5d').rolling(window=3, min_periods=1).mean()

def avgAge(country):
    return ucb_w_reindex_age.loc[ucb_w_reindex_age['country_destination'] == country].age.mean()

num_plots = 10
fig, axes = plt.subplots(3, 4,figsize=(20, 15))
labels = ["01/10", "09/10", "05/11", "02/12", "10/12", "06/13", "02/14"]

list_of_dfs = [{'country': item, 'age': ageSeries(item), 'avgAge': avgAge(item)} for item in ['US', 'FR', 'AU', 'PT', 'CA', 'DE', 'ES', 'GB', 'IT', 'NL']]

colors = ['blue', 'green', 'red', 'orange', 'purple', 'blue', 'green', 'red', 'orange', 'purple']
col, row, loop = (0, 0, 0)
for obj in list_of_dfs:
    row = math.floor(loop/4)

    sns.tsplot(data=obj['age'], color=colors[loop], ax=axes[row, col])
    axes[row, col].set_title('{}'.format(full_country_names[obj['country']]))
    axes[row, col].axhline(obj['avgAge'], color='black', linestyle='dashed', linewidth=4)
    axes[row, col].set(ylim=(20, 65))
    axes[row, col].set_xticklabels(labels, rotation=0)
    axes[row, col].set_xlim(0, 335)

    if col == 0:
        axes[row, col].set(ylabel='Average Age')

    col += 1
    loop += 1

    if col == 4:
        col = 0

fig.suptitle('Age Over Time', fontsize=30)
plt.show()

Facet Grid *我知道在 S.O 中使用图像似乎是禁忌,但确实没有办法将其放入代码中。

我假设你用

生成你的子图
fig, axes = plt.subplots(3, 4,figsize=(20, 15))

不是 seaborn.FacetGrid,如您的示例代码所示。您首先需要做的是以某种方式弄清楚您想要删除哪些地块以及它们在 axes 中的正确索引是什么。然后你可以使用 matplotlib.figure.Figure.delaxes() 删除你不想要的子图。这是一个例子:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(3, 4,figsize=(20, 15))
fig.delaxes(axes[2, 2])
fig.delaxes(axes[2, 3])
plt.show()

Delete subplots from seaborn.FacetGrid有点相似。唯一的小细节是您可以通过 g.axes:

访问 axes
import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="time", row="smoker", sharex=False, sharey=False)
g.fig.delaxes(g.axes[1, 1])
plt.show()