matplotlib

时间:2017-01-10 14:05:59

标签: python matplotlib seaborn

Plots

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

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)

我期待这两个factorplots并排,但不仅如此,我最终得到了两个额外的空白子图,如上所示

已编辑:图片不存在

1 个答案:

答案 0 :(得分:6)

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)

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