简体   繁体   中英

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?

在此处输入图片说明

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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