2017-07-20 15 views
2

我在Jupyter筆記本上寫代碼,並且有一個Seaborn facetgrid,我想要4列和3行。每個小區都是針對10個國家/地區列表中的不同國家/地區。由於總共有12個網格,最後兩個網格是空的,有沒有辦法擺脫最後兩個網格?製作尺寸爲5 x 2的解決方案不是一種選擇,因爲很難看出何時將許多地塊拼湊在一起。截斷Seaborn Faceggrid中的空網格是否可能?

代碼:

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() 

刻面網格*我知道有圖像似乎是禁忌在這裏S.O.,但theres實在不是一個辦法把這個代碼。

enter image description here

回答

3

我假設你

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() 

enter image description here

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() 

enter image description here

+0

啊,對不起,我想我使用次要情節,而不是一個小網格。你的解決方案雖然工作!謝謝Y. Lou – JBT

+0

@TimothyJosephBaney爲了防備'seaborn.FacetGrid'增加了代碼。請檢查是否需要。 –