TJB*_*TJB 3 matplotlib ipython seaborn facet-grid
我正在 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()
Run Code Online (Sandbox Code Playgroud)
Facet Grid *我知道在 SO 中使用图像似乎是禁忌,但实际上没有办法将其放入代码中。
我假设你用
fig, axes = plt.subplots(3, 4,figsize=(20, 15))
Run Code Online (Sandbox Code Playgroud)
不是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()
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
969 次 |
| 最近记录: |