简体   繁体   English

Pandas DataFrame-如何制作堆积面积图堆栈(matplotlib)

[英]Pandas DataFrame - How to make a stacked area graph stack (matplotlib)

I am trying to convert data in a pandas DataFrame in to a stacked area graph but can not seem to get it to stack. 我正在尝试将pandas DataFrame中的数据转换为堆叠的面积图,但似乎无法将其堆叠。

The data is in the format 数据格式为

index | datetime (yyyy/mm/dd) | name | weight_change

With 6 different people each measured daily. 每天测量6位不同的人。

I want the stacked graph to show the weight_change (y) over the datetime (x) but with weight_change for each of the 6 people stacked on top of each other 我希望堆叠图显示日期时间(x)上的weight_change(y),但堆叠在一起的6个人中每个人的weight_change

The closest I have been able to get to it is with: 我能找到的最接近的是:

df = df.groupby['datetime', 'name'], as_index=False).agg({'weight_change': 'sum'})
agg = df.groupby('datetime').sum()
agg.plot.area()

This produces the area graph for the aggregate of the weight_change values (sum of each persons weight_change for each day) but I can't figure out how to split this up for each person like the different values here: 这将生成用于weight_change值(每个人每天的weight_change的总和)的总和的面积图,但是我无法弄清楚如何像下面的不同值那样为每个人将其拆分:

在此处输入图片说明

I have tried various things with no luck. 我没有运气就尝试了各种事情。 Any ideas? 有任何想法吗?

A simplified version of your data: 数据的简化版本:

df = pd.DataFrame(dict(days=range(4)*2,
                       change=np.random.rand(8)*2.,
                       name=['John',]*4 + ['Jane',]*4))

df : df

    change  days    name
0   0.238336    0   John
1   0.293901    1   John
2   0.818119    2   John
3   1.567114    3   John
4   1.295725    0   Jane
5   0.592008    1   Jane
6   0.674388    2   Jane
7   1.763043    3   Jane

Now we can simply use pyplot 's stackplot : 现在我们可以简单地使用pyplotstackplot

import matplotlib.pyplot as plt

days = df.days[df.name == 'John']
plt.stackplot(days, df.change[df.name == 'John'],
              df.change[df.name == 'Jane'])

This produces the following plot: 这将产生以下图:

在此处输入图片说明

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

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