Mefitico
Mefitico

Reputation: 1116

plot data from two DataFrames with different dates

I'm trying to plot data from two dataframes in the same figure. The problem is that I'm using calendar dates for my x axis, and pandas apparently does not like this. The code below shows a minimum example of what I'm trying to do. There are two datasets with some numeric value associated with calendar dates. the data on the second data frame is posterior to the data on the first data frame. I wanted to plot them both in the same figure with appropriate dates and different line colors. the problem is that the pandas.DataFrame.plot method joins the starting date of both dataframes in the chart, thus rendering the visualization useless.

import pandas as pd
import matplotlib.pyplot as plt

df1 = pd.DataFrame({'date': ['2020-03-10', '2020-03-11', '2020-03-12', '2020-03-13', '2020-03-14', '2020-03-15'],
                    'number': [1, 2, 3, 4, 5, 6]})

df2 = pd.DataFrame({'date': ['2020-03-16', '2020-03-17', '2020-03-18', '2020-03-19'],
                    'number': [7, 6, 5, 4]})


ax = df1.plot(x='date', y='number', label='beginning')
df2.plot(x='date', y='number', label='ending', ax=ax)

plt.show()

The figure created looks like this:

enter image description here

Is there any way I can fix this? Could I also get dates to be shown in the x-axis tilted so they're also more legible?

Upvotes: 1

Views: 1455

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

You need to cast 'date' to datetime dtype using pd.to_datetime:

import pandas as pd
import matplotlib.pyplot as plt

df1 = pd.DataFrame({'date': ['2020-03-10', '2020-03-11', '2020-03-12', '2020-03-13', '2020-03-14', '2020-03-15'],
                    'number': [1, 2, 3, 4, 5, 6]})

df2 = pd.DataFrame({'date': ['2020-03-16', '2020-03-17', '2020-03-18', '2020-03-19'],
                    'number': [7, 6, 5, 4]})

df1['date'] = pd.to_datetime(df1['date'])
df2['date'] = pd.to_datetime(df2['date'])
ax = df1.plot(x='date', y='number', label='beginning')
df2.plot(x='date', y='number', label='ending', ax=ax)

plt.show()

Output:

enter image description here

Upvotes: 5

Related Questions