matplotlib中不需要的空白子图

chr*_*a93 4 python matplotlib seaborn

情节

我是matplotlib和seaborn的新手,目前正在尝试使用经典的titanic数据集练习这两个库。这可能是基本的,但是我试图通过输入参数ax = matplotlib axis来并排绘制两个因子图,如以下代码所示:

import matploblib.pyplot as plt
import seaborn as sns
%matplotlib inline 

fig, (axis1,axis2) = plt.subplots(1,2,figsize=(15,4))
sns.factorplot(x='Pclass',data=titanic_df,kind='count',hue='Survived',ax=axis1)
sns.factorplot(x='SibSp',data=titanic_df,kind='count',hue='Survived',ax=axis2)
Run Code Online (Sandbox Code Playgroud)

我原本期望两个因子图同时出现,但不仅如此,我还获得了两个额外的空白子图,如上所示

编辑:图像不存在

Imp*_*est 7

sns.factorplot()尽管将内容绘制到现有的轴(axes1axes2)上,但任何对的调用实际上都会创建一个新图形。这些数字与原始图一起显示fig

我想防止这些未使用的数字出现的最简单方法是使用关闭它们plt.close(<figure number>)

这是笔记本的解决方案

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
%matplotlib inline

titanic_df = pd.read_csv(r"https://github.com/pcsanwald/kaggle-titanic/raw/master/train.csv")

fig, (axis1,axis2) = plt.subplots(1,2,figsize=(15,4))
sns.factorplot(x='pclass',data=titanic_df,kind='count',hue='survived',ax=axis1)
sns.factorplot(x='sibsp',data=titanic_df,kind='count',hue='survived',ax=axis2)
plt.close(2)
plt.close(3)
Run Code Online (Sandbox Code Playgroud)

(对于普通控制台绘图,请删除该%matplotlib inline命令并plt.show()在末尾添加。)