简体   繁体   English

从 Pandas 数据框中绘制堆积条形图

[英]Plot stacked bar chart from pandas data frame

I have dataframe:我有数据框:

payout_df.head(10)

在此处输入图片说明

What would be the easiest, smartest and fastest way to replicate the following excel plot?复制以下 excel 图的最简单、最智能和最快的方法是什么?

在此处输入图片说明

I've tried different approaches, but couldn't get everything into place.我尝试了不同的方法,但无法让一切都到位。

Thanks谢谢

If you just want a stacked bar chart, then one way is to use a loop to plot each column in the dataframe and just keep track of the cumulative sum, which you then pass as the bottom argument of pyplot.bar如果您只想要一个堆积条形图,那么一种方法是使用循环绘制数据pyplot.bar每一列并跟踪累积总和,然后将其作为pyplot.barbottom参数pyplot.bar

import pandas as pd
import matplotlib.pyplot as plt

# If it's not already a datetime
payout_df['payout'] = pd.to_datetime(payout_df.payout)

cumval=0
fig = plt.figure(figsize=(12,8))
for col in payout_df.columns[~payout_df.columns.isin(['payout'])]:
    plt.bar(payout_df.payout, payout_df[col], bottom=cumval, label=col)
    cumval = cumval+payout_df[col]

_ = plt.xticks(rotation=30)
_ = plt.legend(fontsize=18)

在此处输入图片说明

Besides the lack of data, I think the following code will produce the desired graph除了缺乏数据,我认为下面的代码会产生所需的图形

import pandas as pd
import matplotlib.pyplot as plt

df.payout = pd.to_datetime(df.payout)

grouped = df.groupby(pd.Grouper(key='payout', freq='M')).sum()
grouped.plot(x=grouped.index.year, kind='bar', stacked=True)

plt.show()

I don't know how to reproduce this fancy x-axis style.我不知道如何重现这种花哨的 x 轴样式。 Also, your payout column must be a datetime, otherwise pd.Grouper won't work ( available frequencies ).此外,您的payout列必须是日期时间,否则pd.Grouper将不起作用( 可用频率)。

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

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