问题描述
我是 matplotlib 和 seaborn 的新手,目前正在尝试使用经典的 Titanic 数据集来练习这两个库.这可能是基本的,但是我试图通过输入参数ax = matplotlib axis来并排绘制两个因子图,如下代码所示:
I am new to matplotlib and seaborn and is currently trying to practice the two libraries using the classic titanic dataset. This might be elementary, but I'm trying to plot two factorplots side by side by inputting the argument ax = matplotlib axis as shown in the code below:
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)
我原本期待并列两个因子图,但不仅如此,我还获得了两个额外的空白子图,如上所示
I was expecting the two factorplots side by side, but instead of just that, I ended up with two extra blank subplots as shown above
已图像不存在
推荐答案
任何对 sns.factorplot()
的调用实际上都会创建一个新图形,尽管内容被绘制到现有的轴上(axes1
、axes2
).这些数字与原始 fig
一起显示.
Any call to sns.factorplot()
actually creates a new figure, although the contents are drawn to the existing axes (axes1
, axes2
). Those figures are shown together with the original fig
.
我猜想防止那些未使用的图形出现的最简单方法是使用 plt.close(<数字>)
关闭它们.
I guess the easiest way to prevent those unused figures from showing up is to close them, using 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内联
命令,并在最后添加 plt.show()
.)
(For normal console plotting, remove the %matplotlib inline
command and add plt.show()
at the end.)
这篇关于matplotlib中不需要的空白子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!