'Stacked Bar Chart with Total values on Top Python
Here is my data :
import pandas as pd
import matplotlib.pyplot as plt
data = {'Client': ['Client_1', 'Client_2', 'Client_3'],
'Currency': ['USD','USD','USD'],
'Product_1': [1200, 1400, 3300],
'Product_2': [3000, 500, 550],
'Product_3': [200, 4000, 100],
'Product_4': [3000, 0, 100]}
DF = pd.DataFrame(data)
DF['Total Purchases'] = DF.sum(axis=1, numeric_only=True)
print(DF)
I used stacked bar plot tool to plot the data.
DF.drop(columns='Total Purchases').plot(x='Client', kind='bar', stacked=True, figsize=(10,10)).legend(loc='upper center', ncol=5, title="Prices")
Question : How to add for every product its price and the value of 'Total Purchases' for each cleint on top of every Stacked bars ?
Thank you in advance.
Solution 1:[1]
This function should help.
def addlabels(x,y):
for i in range(len(x)):
plt.text(i, y[i], y[i], ha = 'center')
I don't know your initial code; this is what I tried to reproduce.
plt.bar(DF['Client'], DF['Product_1'])
plt.bar(DF['Client'], DF['Product_2'], bottom=DF['Product_1'])
plt.bar(DF['Client'], DF['Product_3'], bottom=DF['Product_2']+DF['Product_1'])
plt.bar(DF['Client'], DF['Product_4'], bottom=DF['Product_3']+DF['Product_2']+DF['Product_1'])
plt.legend(['Product_1', 'Product_2', 'Product_3', 'Product_4'])
addlabels(DF['Client'], DF['Total Purchases'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pyaj |


