Pablo Navais
Pablo Navais

Reputation: 189

How to plot pandas DataFrame with date (Year/Month)?

I've got a pandas dataframe populated with the following data :

      Date         val   count
0  2013-01         A        1 
1  2013-01         M        1
2  2013-02         M        2
3  2013-03         B        3
4  2013-03         M        5
5  2014-05         B        1

I'm new to matplotlib and couldn't figure how to plot this data using as Y axis (count), as X axis (Date) and having three separate curves, one for each value of val.

Upvotes: 1

Views: 10381

Answers (3)

Brian
Brian

Reputation: 1604

You can simply set date as your index, groupby the group column(s) ('A'), select which column you'd like to plot, and then use the SeriesGroupby method plot:

df.set_index('Date').groupby('val')['count'].plot(legend=True)

enter image description here

Upvotes: 1

user3483203
user3483203

Reputation: 51155

Using pivot and plot (A isn't showing up because it only has a single point and is getting hidden by the first point of M). You also have to convert your Date column to datetime in order to accurately display the X-Axis:

df.Date = pd.to_datetime(df.Date)
df.pivot(index='Date', columns='val', values='count').plot(marker='o')

enter image description here

If you'd like to show NaN values as zero instead, just use fillna:

df.pivot(index='Date', columns='val', values='count').fillna(0).plot(marker='o')

Upvotes: 2

sundance
sundance

Reputation: 2945

Groupby your value, loop through and plot each line on the same axis:

fig, ax = plt.subplots()
for i, g in df.groupby("val"):
    g.plot(kind="line", x="Date", y="count", ax=ax, label=i)

Upvotes: 1

Related Questions