I have a dataset as below, where Q1,Q2,Q3 are categorical.
JavaScript
x
7
1
Q1,Q2,Q3
2
0 4,1,5
3
1 1,5,1
4
2 1,2,1
5
3 1,4,1
6
4 5,1,5
7
How can I plot the x axis for each column, and y as the count of the value for each column, all in one plot.
Sample out put
Advertisement
Answer
You can use value_counts
on the columns and then plot:
JavaScript
1
3
1
# grouped by quartile
2
df.apply(pd.Series.value_counts).T.plot.bar()
3
JavaScript
1
3
1
# grouped by value
2
df.apply(pd.Series.value_counts).plot.bar()
3
old answer
A quick way using pandas only is:
JavaScript
1
2
1
df.groupby(level=0, axis=1).plot.bar()
2
But this won’t be flexible for the colors/layout.
If you want a nice output, rework your dataframe as long format and use seaborn.catplot
:
JavaScript
1
9
1
import seaborn as sns
2
df2 = (df.unstack()
3
.reset_index()
4
.rename(columns={'level_0': 'quartile',
5
'level_1': 'index',
6
0: 'value'})
7
)
8
sns.catplot(data=df2, col='quartile', x='index', y='value', kind='bar')
9
I used the following input:
JavaScript
1
7
1
Q1 Q2 Q3
2
0 4 1 5
3
1 1 5 1
4
2 1 2 1
5
3 1 4 1
6
4 5 1 5
7
combining both answers:
JavaScript
1
10
10
1
import seaborn as sns
2
df2 = (df.apply(pd.Series.value_counts)
3
.unstack()
4
.reset_index()
5
.rename(columns={'level_0': 'quartile',
6
'level_1': 'index',
7
0: 'counts'})
8
)
9
sns.catplot(data=df2, col='quartile', x='index', y='counts', kind='bar')
10