I have Data Frame like below (for reference):
target |product
---------|--------
1 |EHZ
1 |GBK
0 |EHZ
0 |AKP
1 |AKP
So I have target variable "target" and nominal variable "product" and I woul like to plot graph like below based on my df, how can I do that? I know only that it is stackedbar, and
- I need to have as below that each column have percentage description both for 0 and 1
- and columns have identical heoght and they are divided into 1 and 0
Everything in Python Pandas / Matplotlib. Could you show me example code which makes me identical plot based on my data frame ?
I used code created by Rob Raymond like below:
fig, ax = plt.subplots(figsize=(10,3))
# prepare dataframe for plotting
dfp = pd.crosstab(index=df["product"], columns=df["target"]).apply(lambda r: r/r.sum(), axis=1)
# simple stacked plot
ax = dfp.plot(kind="barh", stacked=True, ax=ax)
for c in ax.containers:
# customize the label to account for cases when there might not be a bar section
labels = [f'{w*100:.0f}%' if (w := v.get_width()) > 0 else '' for v in c ]
# set the bar label
ax.bar_label(c, labels=labels, label_type='center')
ax.set_xlabel("procent")
ax.set_title("tytul")
and I have error like below: