![](/img/trans.png)
[英]Plotly: How to display the total sum of the values at top of a stacked bar chart along with the individual bar values?
[英]Stacked Bar Chart with Total values on Top
这是我的数据:
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)
我使用堆叠条 plot 工具对 plot 数据。
DF.drop(columns='Total Purchases').plot(x='Client', kind='bar', stacked=True, figsize=(10,10)).legend(loc='upper center', ncol=5, title="Prices")
问题:如何为每个产品添加其价格和每个堆叠条顶部每个客户的“总购买量”值?
先感谢您。
这个 function 应该会有所帮助。
def addlabels(x,y):
for i in range(len(x)):
plt.text(i, y[i], y[i], ha = 'center')
我不知道你的初始代码; 这就是我试图重现的内容。
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'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.