从 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
Plot stacked bar chart from pandas data frame
提问by user40
回答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 bottom
argument 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)
回答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 payout
column must be a datetime, otherwise pd.Grouperwon't work (available frequencies).
我不知道如何重现这种花哨的 x 轴样式。此外,您的payout
列必须是日期时间,否则pd.Grouper将不起作用(可用频率)。