在python中堆叠来自不同系列的三个条形图

问题描述 投票:1回答:1

我是matplotlib的新手,无法弄清楚如何将多个系列堆叠成一个条形图。

这是一些数据:

import pandas as pd
import matplotlib.pyplot as plt
###Data
x_lab =  pd.Series(['a','b','c'])
Series1 = pd.Series([25,35,30])
Series2 = pd.Series([40,35,50])
Series3 = pd.Series([35,30,20])

##Creating the 3 bars to plot##
pl_1 = plt.bar(x= x_lab,height = Series1)
pl_2 = plt.bar(x= x_lab,height = Series2)
pl_3 = plt.bar(x= x_lab,height = Series3)

当我运行此代码时,数据会相互叠加。我希望能够堆叠数据。

我试过这个:

##First attempt
attempt_1 = plt.bar(x = x_lab, height = [pl_1,pl_2,pl_3], stacked = True)

还有这个:

##Second Attempt 
pl_1 = plt.bar(x= x_lab,height = Series1, stacked = True)
pl_2 = plt.bar(x= x_lab,height = Series2, stacked = True)
pl_3 = plt.bar(x= x_lab,height = Series3, stacked = True)

但都没有奏效。期望的输出看起来像这样(颜色不需要匹配):enter image description here

任何帮助或指导将不胜感激。

python pandas matplotlib bar-chart stacked-chart
1个回答
3
投票

concat +与stacked=True的酒吧情节

import pandas as pd

(pd.concat([Series1, Series2, Series3], axis=1)
     .assign(idx=x_lab).set_index('idx')       # just for the labeling
     .plot.bar(stacked=True))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.