unwanted blank subplots in matplotlib

大城市里の小女人 提交于 2021-01-27 06:49:43

问题


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

Edited: image was not there


回答1:


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.

I guess the easiest way to prevent those unused figures from showing up is to close them, using plt.close(<figure number>).

Here is a solution for a notebook

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)

(For normal console plotting, remove the %matplotlib inline command and add plt.show() at the end.)



来源:https://stackoverflow.com/questions/41570747/unwanted-blank-subplots-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!