I am working with the following bar plot:
And I would like to add only the total amount of each index on top of the bars, like this:
However, when I use the following code, I only get parts of the stacks of each bar.
JavaScript
x
30
30
1
import matplotlib.pyplot as plt
2
3
data = [['0.01 - 0.1','A'],['0.1 - 0.5','B'],['0.5 - 1.0','B'],['0.01 - 0.1','C'],['> 2.5','A'],['1.0 - 2.5','A'],['> 2.5','A']]
4
5
df = pd.DataFrame(data, columns = ['Size','Index'])
6
7
### plot
8
9
df_new = df.sort_values(['Index'])
10
11
list_of_colors_element = ['green','blue','yellow','red','purple']
12
13
# Draw
14
piv = df_new.assign(dummy=1)
15
.pivot_table('dummy', 'Index', 'Size', aggfunc='count', fill_value=0)
16
.rename_axis(columns=None)
17
ax = piv.plot.bar(stacked=True, color=list_of_colors_element, rot=0, width=1)
18
19
ax.bar_label(ax.containers[0],fontsize=9)
20
21
# Decorations
22
plt.title("Index coloured by size", fontsize=22)
23
plt.ylabel('Amount')
24
plt.xlabel('Index')
25
plt.grid(color='black', linestyle='--', linewidth=0.4)
26
plt.xticks(range(3),fontsize=15)
27
plt.yticks(fontsize=15)
28
29
plt.show()
30
I have tried with different varieties of ax.bar_label(ax.containers[0],fontsize=9)
but none displays the total of the bars.
Any help is appreciated!
Advertisement
Answer
I’m not sure there’s a way to do this with the new bar_label
method, but you can label the totals manually.
Compute the row totals via piv.sum(axis=1)
and annotate
the totals:
JavaScript
1
3
1
for x, y in enumerate(piv.sum(axis=1)):
2
ax.annotate(y, (x, y), ha='center')
3