Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unwanted blank subplots in matplotlib

Plots

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

like image 638
chrishendra93 Avatar asked Mar 10 '23 04:03

chrishendra93


1 Answers

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.)

like image 63
ImportanceOfBeingErnest Avatar answered Mar 13 '23 02:03

ImportanceOfBeingErnest