【问题标题】:Stacking three bar charts from different series in python在python中堆叠来自不同系列的三个条形图
【发布时间】:2019-09-20 09:41:39
【问题描述】:

我是 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)

但都没有奏效。所需的输出看起来像这样(颜色不需要匹配):

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

【问题讨论】:

  • 3 系列,3 个元素,3 种颜色,有点令人困惑。堆栈是每个系列的第一个元素,还是单个系列?绿色似乎太小了,但它们的总和都是 100,所以不确定。
  • 是的,令人困惑..第一个堆栈是所有第一个元素,第二个堆栈是所有第二个元素,第三个堆栈是所有第三个元素。

标签: python pandas matplotlib bar-chart stacked-chart


【解决方案1】:

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))

【讨论】:

  • 把行缩短.plot.bar(stacked=True) :-)
猜你喜欢
  • 1970-01-01
  • 2019-07-19
  • 2023-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
相关资源
最近更新 更多