简体   繁体   English

将 Pandas DF 绘制为堆积条形图,同时忽略缺失值

[英]Plot Pandas DF as stacked bar chart while ignoring missing values

I've got a dataframe with workout logs like this:我有一个带有锻炼日志的数据框,如下所示:

>>> data
       _date  _week  Distance (km)
0 2020-10-31     44      42.220013
1 2020-10-29     44      10.054135
2 2020-10-25     43      30.103745
3 2020-10-24     43      14.135142
4 2020-10-20     43      10.471132
5 2020-10-17     42      27.164278
6 2020-10-15     42      18.511157

And would like to plot it as a stacked-bar chart per week, like this:并希望将其绘制为每周堆积条形图,如下所示:

按周分组的绘图

Problem 1: I can't figure out how to pivot or group by the DF before plotting, given that it's got uneven number of workouts per week, up to 4 or 5, but sometimes none at all when I was lazy.问题 1:在绘图之前我无法弄清楚如何根据 DF 进行旋转分组,因为它每周的锻炼次数是不均匀的,最多 4 或 5 次,但有时在我懒惰的时候根本没有。

Problem 2: Optionally I'd like to sort them from longest to shortest for aesthetics, so that the longest ones are always the same colour and are at the bottom, etc. But it's nit picking :)问题 2:(可选)为了美观,我想将它们从最长到最短进行排序,以便最长的总是相同的颜色并且在底部等。但它是挑剔的 :)

Thanks for any pointers!感谢您的任何指点!

You need to create a new field for Run using cumcount and pivot it to columns with week on the index:您需要使用cumcountRun创建一个新字段,并将其pivot到索引上带有week列:

df['Run'] = 'Run ' + (df.groupby('_week').cumcount() + 1).astype(str)
df = df.drop('_date', axis=1).set_index('_week').pivot(columns='Run')
df.plot(kind='bar', stacked=True)

在此处输入图片说明

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

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