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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With