3

我正在 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 *我知道在 SO 中使用图像似乎是禁忌,但实际上没有办法将其放入代码中。

在此处输入图像描述

4

1 回答 1

7

我假设你生成你的子图

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 fromseaborn.FacetGrid有点类似。唯一的次要细节是您可以axes通过以下方式访问g.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()

在此处输入图像描述

于 2017-07-20T05:49:52.773 回答