Plotting two dataframes into one bar chart, distinguishing their values

Viewed 112

I am confusing myself with the following task and I hope someone can point me to the right direction. I have two datasets, one with data from January 2019 and another one with data from January 2020.

df1

ID     Date
5177   2019-01-31
5178   2019-01-31
5179   2019-01-31
5180   2019-01-31
5181   2019-01-31
5182   2019-01-31
5183   2019-01-31
5184   2019-01-30
5185   2019-01-30
5186   2019-01-30

df2

ID     Date
2918   2020-01-31
2919   2020-01-31
2920   2020-01-31
2921   2020-01-31
2922   2020-01-31
2923   2020-01-31
2924   2020-01-31
2925   2020-01-31
2926   2020-01-30
2927   2020-01-30

I tried to plot them as line charts as follows:

df1.groupby('Date').size().plot()
df2.groupby('Date').size().plot()

plt.xticks(rotation=90)
plt.show() 

but the output is not good as the results are shown in two different areas of the chart (one is 2019 and another one is 2020). So what I have been trying to do is to plot these data as bar charts, putting bars close to each other in order to easily compare the frequency of data day by day through months.

I have tried as follows:

df1.groupby(['Date'])['Date'].size().plot(kind='bar')
df2.groupby(['Date'])['Date'].size().plot(kind='bar')

but this does not distinguish between values from df1 and values from df2 (also, bars are in the same colour).

What I would like to have is a chart with on the x-axis the date (only days, as months are the same and I know which year I am comparing). With different colour, I would need to plot data from 1 and data from 2 (the legend will tell which df1/2 is).

Can you please tell me how to plot data to get the expected output?

Thanks

1 Answers

You can join into one dataframe first, but first change the format of your dates to '%m-%d' with strftime, and you can also rename the output of the size column to the year.

df1['Date'] = pd.to_datetime(df1['Date']).dt.strftime('%m-%d')
df2['Date'] = pd.to_datetime(df2['Date']).dt.strftime('%m-%d')
(df1.groupby('Date').size().rename('Size').to_frame().join(
    df2.groupby('Date').size().rename('Size').to_frame(),
    lsuffix='_2019', rsuffix='_2020').plot(kind='bar'))

enter image description here

Related