0

I have a Pandas DataFrame, for example:

pd.DataFrame({
    "A": [165,166,920,920,920,165,162,162,166,165,755,469],
    "B": [1920,868,470,470,698,945,1670,575,701,1920,1920,470],
    "C": [1670,461,461,212,212,212,212,414,453,196,254,461]
})

I would like to have a seaborn countplot of each option A, B and C with the top 2 for each column plotted side by side.

Below is an image of something similar. My problem is getting the columns side by side with the legend.

Something similar to this

Thanks

1 Answer 1

2

Can you try this?

import pandas as pd
import seaborn as sns

df=pd.DataFrame({
"A": [165,166,920,920,920,165,162,162,166,165,755,469],
"B": [1920,868,470,470,698,945,1670,575,701,1920,1920,470],
"C": [1670,461,461,212,212,212,212,414,453,196,254,461]})


sns.set(style="darkgrid")
fig, ax =plt.subplots(3,1)
max_count = max([max(df[i].value_counts()) for i in df.columns])
A=sns.countplot(y=df['A'],ax=ax[0],order=df.A.value_counts().iloc[:2].index)
B=sns.countplot(y=df['B'],ax=ax[1],order=df.B.value_counts().iloc[:2].index)
C=sns.countplot(y=df['C'],ax=ax[2],order=df.C.value_counts().iloc[:2].index)
ax[0].set_xlim(0,max_count)
ax[1].set_xlim(0,max_count)
ax[2].set_xlim(0,max_count)
A.set(xticklabels=[])
B.set(xticklabels=[])

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

How can I set the overall title. Set and set_title does not work
@A.JT, use this: ax[0].set_title(<title>) Let me know if this works for you. :)
Happy to have helped you, @A.JT! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.