user40
user40

Reputation: 1400

How to plot aggregated by date pandas dataframe

I have this dataframe

df=pd.DataFrame([["2017-01-14",1],
    ["2017-01-14",30],
    ["2017-01-16",216],
    ["2017-02-17",23],
    ["2017-02-17",2],
    ["2017-03-19",745],
    ["2017-03-19",32],
    ["2017-03-20",11],
    ["2017-03-20",222],
    ["2017-03-21",4]],columns=["date","payout_value"])

To aggregate payout_value by date I use:

df_daily=df.groupby('date').agg(['sum'])

payout_value
sum
date    
2017-01-14  31
2017-01-16  216
2017-02-17  25
2017-03-19  777
2017-03-20  233
2017-03-21  4

How do I plot (bar chart) dates on x-axis and aggregated payout sum on y axis?

I tried using df.plot(x='date', y='payout_value',kind="bar") approach, but there is no 'date' column in df_daily dataframe, print(list(df_daily)) gives [('payout_value', 'sum')]

Upvotes: 10

Views: 17717

Answers (4)

dh7hong
dh7hong

Reputation: 1

The simplest I can code is:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df=pd.DataFrame([["2017-01-14",1],
    ["2017-01-14",30],
    ["2017-01-16",216],
    ["2017-02-17",23],
    ["2017-02-17",2],
    ["2017-03-19",745],
    ["2017-03-19",32],
    ["2017-03-20",11],
    ["2017-03-20",222],
    ["2017-03-21",4]], columns=["date","payout_value"])

df.groupby('date').agg('sum').plot(kind='bar', y='payout_value')
plt.show()

link to the bar plot

Upvotes: 0

BENY
BENY

Reputation: 323226

You can set_index and sum

df.assign(date=pd.to_datetime(df.date)).set_index('date').payout_value.sum(level=0).plot(kind='bar')

enter image description here

Upvotes: 3

Mohamed Thasin ah
Mohamed Thasin ah

Reputation: 11192

you are almost there, use reset_index and plot your by df_daily

df_daily=df.groupby('date').agg(['sum']).reset_index()
df_daily.plot(x='date', y='payout_value',kind="bar")
plt.show()

enter image description here

Upvotes: 18

sacuL
sacuL

Reputation: 51335

Try:

df.groupby('date').agg(['sum']).plot.bar(legend='')
plt.xlabel('date')
plt.ylabel('payout value sum')

enter image description here

Upvotes: 3

Related Questions