0

I have a dataframe that looks like below, the date is the index. How would I plot a time series showing a line for each of the years? I have tried df.plot(figsize=(15,4)) but this gives me one line.

Date       Value
2008-01-31   22
2008-02-28   17
2008-03-31   34
2008-04-30   29
2009-01-31   33
2009-02-28   42
2009-03-31   45
2009-04-30   39 
2019-01-31   17
2019-02-28   12  
2019-03-31   11 
2019-04-30   12
2020-01-31   24
2020-02-28   34
2020-03-31   43
2020-04-30   45
a_1995
  • 45
  • 6
  • Does this answer your question? [Pandas dataframe groupby plot](https://stackoverflow.com/questions/41494942/pandas-dataframe-groupby-plot) – Trenton McKinney May 12 '20 at 18:24

2 Answers2

0

You can just do a groupby using year.

df = pd.read_clipboard()
df = df.set_index(pd.DatetimeIndex(df['Date']))
df.groupby(df.index.year)['Value'].plot()

enter image description here

Matthew Borish
  • 3,016
  • 2
  • 13
  • 25
0

In case you want to use year as series of data and compare day to day:

import matplotlib.pyplot as plt

# Create a date column from index (easier to manipulate)
df["date_column"] = pd.to_datetime(df.index)

# Create a year column
df["year"] = df["date_column"].dt.year

# Create a month-day column
df["month_day"] = (df["date_column"].dt.month).astype(str).str.zfill(2) + \
                "-" + df["date_column"].dt.day.astype(str).str.zfill(2)

# Plot. Pivot will create for each year a column and these columns will be used as series.
df.pivot('month_day', 'year', 'Value').plot(kind='line', figsize=(12, 8), marker='o' )
plt.title("Values per Month-Day - Year comparison", y=1.1, fontsize=14)
plt.xlabel("Month-Day", labelpad=12, fontsize=12)
plt.ylabel("Value", labelpad=12,  fontsize=12);  

enter image description here

Marcos
  • 786
  • 7
  • 8