简体   繁体   English

组合两个堆叠条形图以获得分组堆叠条 plot

[英]Combining two stacked bar plots for a grouped stacked bar plot

So I found the following code online:于是我在网上找到了如下代码:

import matplotlib.pyplot as plt
import matplotlib

matplotlib.style.use('ggplot')

plotdata = pd.DataFrame({
    "2018_m":[40, 12, 10, 26, 36],
    "2019_m":[19, 8, 30, 21, 38],
    "2020_m":[10, 10, 42, 17, 37]
    }, index=["Dad", "Mam", "Bro", "Sis", "Me"]
)

plotdata2 = pd.DataFrame({
    "2018_y":[20, 22, 10, 34, 12],
    "2019_y":[12, 19, 27, 35, 14],
    "2020_y":[21, 31, 52, 20, 34]
    }, index=["Dad", "Mam", "Bro", "Sis", "Me"]
)

stacked_data = plotdata.apply(lambda x: x*100/sum(x), axis=1)
stacked_data2 = plotdata2.apply(lambda x: x*100/sum(x), axis=1)
stacked_data.plot(kind="bar", stacked=True)
stacked_data2.plot(kind="bar", stacked=True)

And this is the output:这是 output:

在此处输入图像描述

I was wondering what would be the best way to combine them so that Dad, Mam, Bro etc. each have two stacked bars?我想知道将它们组合在一起的最佳方法是什么,以便爸爸、妈妈、兄弟等每个人都有两个堆叠的条? I've come across a bunch of other grouped stacked bar codes online and elsewhere on Stack Overflow but they require you to iteratively define which values you have for each bar, whereas ideally I'd want to just have to reference the dataframe names 'plotdata' and 'plotdata2' like in the code above.我在 Stack Overflow 上和其他地方在线和其他地方遇到过一堆其他分组堆叠条码,但它们要求您迭代地定义每个条的值,而理想情况下,我只想引用 dataframe 名称'plotdata ' 和 'plotdata2' 就像上面的代码一样。

Thanks in advance!提前致谢!

For two groups, you can pass position and adjust the width accordingly:对于两组,您可以通过position并相应调整宽度:

fig, ax = plt.subplots()

stacked_data.plot(kind="bar", stacked=True, width=0.4, 
                  ax=ax, position=0)
stacked_data2.plot(kind="bar", stacked=True, width=0.4, 
                   ax=ax, position=1, hatch='//')

ax.set_xlim(right=len(stacked_data)-0.5)

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM