1

I cannot subplot catplot. Here is my code:

import seaborn as sns
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1,2)
sns.catplot(x='species', y='sepal_length', data=df , kind='violin')
sns.catplot(x='species', y='sepal_width', data=df , kind='violin')

And here is the output: How can I fix it? Thank you.

enter image description here enter image description here enter image description here

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Data Pagla
  • 365
  • 1
  • 3
  • 6

2 Answers2

3

Although this may be a promotion of my package, patchworklib allows you to handle catplot plots as matplotlib subplots. Please see the following code.

import seaborn as sns
import matplotlib.pyplot as plt
import patchworklib as pw
pw.overwrite_axisgrid()

df = sns.load_dataset('iris')
g1 = sns.catplot(x='species', y='sepal_length', data=df , kind='violin')
g1 = pw.load_seaborngrid(g1)

g2 = sns.catplot(x='species', y='sepal_width', data=df , kind='violin')
g2 = pw.load_seaborngrid(g2) 

(g1|g2).savefig()

enter image description here

You can also align them vertically as follow.

(g1/g2).savefig()

enter image description here

The code above is executable in Google colab.

Hideto
  • 320
  • 3
  • 5
2

catplot creates its own new figure. You can either use catplot on a "long form dataframe" (using pd.melt()), or create individual sns.violinplots on each ax.

Using subplots with violinplot:

import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')
fig, axes = plt.subplots(1, 2)
sns.violinplot(x='species', y='sepal_length', data=df, ax=axes[0])
sns.violinplot(x='species', y='sepal_width', data=df, ax=axes[1])
plt.tight_layout()
plt.show()

Using catplot with long form dataframe:

import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')
df_long = df.melt(id_vars='species', value_vars=['sepal_length', 'sepal_width'])

sns.catplot(x='species', y='value', col='variable', data=df_long, kind='violin')
plt.tight_layout()
plt.show()

sns.catplot with long form dataframe

JohanC
  • 71,591
  • 8
  • 33
  • 66