Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a restriction on catplot with subplot?

Seaborn's catplot does not seem to be able to work with plt.subplots(). Am not sure whats the issue here but i dont seem to be able to put them side by side.

#Graph 1
plt.subplot(121)
sns.catplot(x="HouseStyle",y="SalePrice",data=df,kind="swarm")

#Graph 2
plt.subplot(122)
sns.catplot(x="LandContour",y="SalePrice",data=df,kind="swarm")

Output: Weird no output Weird no output2 Finally output

like image 338
Aaron Avatar asked Jun 27 '19 09:06

Aaron


3 Answers

Catplot is a figure-level function whereas you cannot use axes. Try using stripplot instead.

fig, axs = plt.subplots (1, 2, figsize=(25, 15))
sns.stripplot(x='category_col', y='y_col_1', data=df, ax=axs[0])
sns.stripplot(x='category_col', y='y_col_2', data=df, ax=axs[1])
like image 173
m_h Avatar answered Oct 18 '22 21:10

m_h


You need to pass the created axis to seaborn's catplot while plotting. Following is a sample answer demonstrating this. A couple of things

  • I would suggest using add_subplot to create subplots like yours
  • The catplot will still return an axis object which can be closed using plt.close() where the number inside the brackets correspond to the figure count. See this answer for more details on close()

Complete reproducible answer

import seaborn as sns
import matplotlib.pyplot as plt

exercise = sns.load_dataset("exercise")

fig = plt.figure()

ax1 = fig.add_subplot(121)
g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise, ax=ax1) # pass ax1

ax2 = fig.add_subplot(122)
g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise, ax=ax2) # pass ax2

plt.close(2)
plt.close(3)
plt.tight_layout()

enter image description here

like image 23
Sheldore Avatar answered Oct 18 '22 21:10

Sheldore


Thank you Sheldore for giving an idea of using close(). I tried this way and it worked.

_, ax = plt.subplots(2, 3, figsize=(20,10))
for n, feat in enumerate(cat_feats):
        sns.catplot(x='feat', kind='count', data=df, ax=ax[n//3][n%3])
        plt.close()
like image 1
Ravi Vuppala Avatar answered Oct 18 '22 21:10

Ravi Vuppala