Sub Plots using Seaborn

I am trying to plot box plots and violin plots for three variables against a variable in a 3X2 subplot formation. But I am not able to figure out how to include sns lib with subplot function.

#plots=plt.figure()
axis=plt.subplots(nrows=3,ncols=3)
for i,feature in enumerate(list(df.columns.values)[:-1]):
    axis[i].plot(sns.boxplot(data=df,x='survival_status_after_5yrs',y=feature))
    i+=1
    axis[i].plot(sns.violinplot(data=df,x='survival_status_after_5yrs',y=feature))
plt.show()```

I am expecting 3X2 subplot, x axis stays same all the time y axis rolls over the three variables I have mentioned.

Thanks for your help.

Upvotes: 0

Views: 520

Answers (2)

Robert King
Robert King

Reputation: 994

I think you have two problems.

First, plt.subplots(nrows=3, ncols=2) returns a figure object and an array of axes objects so you should replace this line with: fig, ax = plt.subplots(nrows=3, ncols=2). The ax object is now a 3x2 numpy array of axes objects.

You could turn this into a 1-d array with ax = ax.flatten() but given what I think you are trying to do I think it is easier to keep as 3x2. (Btw I assume the ncols=3 is a typo)

Second, as Ewoud answer mentions with seaborn you pass the axes to plot on as an argument to the plot call.

I think the following will work for you:

fig, ax = plt.subplots(nrows=3, ncols=2)
for i, feature in enumerate(list(df.columns.values)[:-1]):
    # for each feature create two plots on the same row
    sns.boxplot(data=df, x='survival_status_after_5yrs',y=feature, ax=ax[i, 0])
    sns.violinplot(data=df, x='survival_status_after_5yrs', y=feature, ax=ax[i, 1])
plt.show()

Upvotes: 1

Ewoud
Ewoud

Reputation: 751

Most seaborn plot functions have an axis kwarg, so instead of

axis[i].plot(sns.boxplot(data=df,x='survival_status_after_5yrs',y=feature))

try

sns.boxplot(data=df,x='survival_status_after_5yrs',y=feature,axis=axis[i])

Upvotes: 0

Related Questions