Ray92
Ray92

Reputation: 453

How to combine multiple seaborn countplots with a shared y axis

Hi I am trying to combine multiple seaborn countplots. So I am using the following code to make plot number one (shown below):

ax=sns.countplot(x="CommsMail", data=df, palette="Greens_d",
          order=df.CommsMail.value_counts().iloc[:5].index)
ax.set_xticklabels(ax.get_xticklabels(), rotation=90, ha="right")
plt.tight_layout()
plt.show()

enter image description here

And I am using the following code to make plot number two (shown below):

ax1=sns.countplot(x="CommsMailSecondary", data=df, palette="Greens_d",
              order=df.CommsMailSecondary.value_counts().iloc[:5].index)
ax1.set_xticklabels(ax.get_xticklabels(), rotation=90, ha="right")
plt.tight_layout()
plt.show()

enter image description here

My question is - how do I combine these two (or more) countplots so that the "True / False" is the legend, with a common y axis (shown below)? I have search the internet a lot but cant seem to find a way to combine this particular type of seaborn countplot, Thanks.

Desired plot:

enter image description here

Upvotes: 0

Views: 480

Answers (1)

Sergey Bushmanov
Sergey Bushmanov

Reputation: 25249

You can easily do it in pandas only:

df_new = df.apply(pd.value_counts).T
ax=df_new.plot.bar()
ax.set_xticklabels(ax.get_xticklabels(), rotation=90, ha="right")
plt.tight_layout()
plt.show();

enter image description here

Upvotes: 1

Related Questions