I would like to make a graph using seaborn. I have three types that are called 1, 2 and 3. In each type, there are groups P and F. I would like to present the graph in a way that each bin sums up to 100% and shows how many of each type are of group P and group F. I would also like to show the types as categorical rather than interpreted as numbers.
Could someone give me suggestions how to adapt the graph?
So far, I have used the following code:
JavaScript
x
2
1
sns.displot(data=df, x="TYPE", hue="GROUP", multiple="stack", discrete=1, stat="probability")
2
And this is the graph:
Advertisement
Answer
The option multiple='fill'
stretches all bars to sum up to 1 (for 100%). You can use the new ax.bar_label()
to label each bar.
JavaScript
1
15
15
1
import matplotlib.pyplot as plt
2
import seaborn as sns
3
import pandas as pd
4
import numpy as np
5
6
np.random.seed(12345)
7
df = pd.DataFrame({'TYPE': np.random.randint(1, 4, 30),
8
'GROUP': np.random.choice(['P', 'F'], 30, p=[0.8, 0.2])})
9
g = sns.displot(data=df, x='TYPE', hue='GROUP', multiple='fill', discrete=True, stat='probability')
10
ax = g.axes.flat[0]
11
ax.set_xticks(np.unique(df['TYPE']))
12
for bars in ax.containers:
13
ax.bar_label(bars, label_type='center', fmt='%.2f' )
14
plt.show()
15