我是 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)
我原以为这两个因子图是并排的,但不仅如此,我还得到了两个额外的空白子图,如上所示
已编辑:图像不存在
最佳答案
任何调用 sns.factorplot()
实际上创建了一个新图形,尽管内容被绘制到现有轴( axes1
, axes2
)。这些数字与原始 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)
(对于普通控制台绘图,删除 %matplotlib inline
命令并在末尾添加 plt.show()
。)
关于python - matplotlib 中不需要的空白子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41570747/