pandas dataframe overlapping time data on plot

Viewed 90

I've got this code generating the figure below.

in

yearly_data = { 2021: <..series..> , 2022: <..series..>}
print(type(yearly_data[2021]))

out

<class 'pandas.core.series.Series'>

in

df = pd.DataFrame(yearly_data)
print(df.axes)

out

[DatetimeIndex(['2011-01-04', '2011-01-05', '2011-01-06', '2011-01-07',
               '2011-01-10', '2011-01-11', '2011-01-12', '2011-01-13',
               '2011-01-14', '2011-01-18',
               ...
               '2021-03-25', '2021-03-26', '2021-03-29', '2021-03-30',
               '2021-03-31', '2021-04-01', '2021-04-05', '2021-04-06',
               '2021-04-07', '2021-04-08'],
              dtype='datetime64[ns]', name='Date', length=2572, freq=None), Int64Index([2021, 2020, 2019, 2018, 2017, 2016, 2015, 2014, 2013, 2012, 2011], dtype='int64')]

in

title = 'comparison of yearly data'
plot = df.plot(figsize=(25,25), title=title)
figure = plot.get_figure()
figure.savefig(title + '.pdf')

out

enter image description here

basically every year data is plotted on the same axis and it's on the side of the other years, I'd like every year line to be on top of the others, so that it's easy to visually compare them.

1 Answers

you can do it by groupby the month-day from the index and use first that would align all the years on the same date without the year:

#toy data
np.random.seed(12)
yearly_data = {
    2021:pd.Series(np.random.randint(40,50, size=365), 
                   index = pd.date_range('2021-01-01','2021-12-31',freq='d')),
    2020:pd.Series(np.random.randint(30,45, size=366), 
                   index = pd.date_range('2020-01-01','2020-12-31',freq='d'))
}
# put data together
df = pd.DataFrame(yearly_data)

# here groupby and first
df.groupby(df.index.strftime('%m-%d')).first().plot()

Another possibility is to create another dictionary with the series with the index independent of the year, then df.plot will give the same output

yearly_data_MD = {}
for year, ser in yearly_data.items():
    ser_ = ser.copy()
    ser_.index = ser_.index.strftime('%m-%d')
    yearly_data_MD[year] = ser_
df = pd.DataFrame(yearly_data_MD)
df.plot()
Related