从 pandas 数据框中绘制堆积的条形图 [英] Plot stacked bar chart from pandas data frame

查看:120
本文介绍了从 pandas 数据框中绘制堆积的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据框:

payout_df.head(10)

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

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

我尝试了不同的方法,但是无法将所有内容都放在适当的位置.

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

谢谢

推荐答案

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

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

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)

这篇关于从 pandas 数据框中绘制堆积的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆