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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49889398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:28:57  来源:igfitidea点击:

Plot stacked bar chart from pandas data frame

pythonpandasdataframematplotlibplot

提问by user40

I have dataframe:

我有数据框:

payout_df.head(10)

payout_df.head(10)

enter image description here

在此处输入图片说明

What would be the easiest, smartest and fastest way to replicate the following excel plot?

复制以下 excel 图的最简单、最智能和最快的方法是什么?

enter image description here

在此处输入图片说明

I've tried different approaches, but couldn't get everything into place.

我尝试了不同的方法,但无法让一切都到位。

Thanks

谢谢

回答by ALollz

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 bottomargument of pyplot.bar

如果您只想要一个堆积条形图,那么一种方法是使用循环绘制数据框中的每一列并跟踪累积总和,然后将其作为bottom参数传递pyplot.bar

import pandas as pd
import matplotlib.pyplot as plot

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

enter image description here

在此处输入图片说明

回答by gmacro

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. Also, your payoutcolumn must be a datetime, otherwise pd.Grouperwon't work (available frequencies).

我不知道如何重现这种花哨的 x 轴样式。此外,您的payout列必须是日期时间,否则pd.Grouper将不起作用(可用频率)。