![](/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.