Lasse
Lasse

Reputation: 141

How to compare graphically two pandas dataframe where index is datetime

I am measuring temperature data and I get .csv like this:

Date/Time,to [°C]
06.12.2018 11:56:07,-26.2
06.12.2018 11:56:09,-26.2
06.12.2018 11:56:11,-26.2
06.12.2018 11:56:13,-26.2
06.12.2018 11:56:15,-26.2

I'd like to plot values of two same kind of measurements made in two different time spans. So do I need to normalize datetimes or how do I make them comparable in lineplot? Thanks for help.

Upvotes: 1

Views: 115

Answers (2)

yatu
yatu

Reputation: 88276

Create an independent axis using ax.twiny

Here's a way to do it. Say you have the following dataframes:

df1 = pd.DataFrame({'date1':['06.12.2018 11:56:07', '06.12.2018 11:56:09', '06.12.2018 11:56:11', '06.12.2018 11:56:13' ],
               'temp': [20.7,13,7,30]})
df2 = pd.DataFrame({'date2':['06.12.2018 21:56:07', '06.12.2018 21:56:09', '06.12.2018 21:56:11', '06.12.2018 21:56:13' ],
               'temp': [3,-2,-5,3]})
df1.date1 = pd.to_datetime(df1.date1)
df2.date2 = pd.to_datetime(df2.date2)

You can create an additional x-axis by using ax.twiny(), which will create a twin axis sharing the yaxis. This way you can have both sequences in the same plot, and you don't lose the date information:

fig = plt.figure(figsize=(15,8))
ax = fig.add_subplot(111)
df1.plot(x='date1', y = 'temp', ax=ax, label='df1', c='red')
ax2 = ax.twiny()
df2.plot(x='date2', y = 'temp', ax=ax2, label = 'df2', c='blue')

enter image description here

Upvotes: 1

Neo
Neo

Reputation: 627

Do you mean that you want to ignore timestamps when plotting to compare values? Here is how to plot two timeseries together without timestamps. I have added a second list with random temperatures.

import matplotlib.pyplot as plt
import numpy as np
other_list = [-23,-29,-10 ,0,3]
t = np.arange(len(df))
plt.figure(figsize=(10,7))
plt.plot( t,df['to [°C]'].values, 'r--s',t, other_list, 'b--s')
plt.legend(('FirstDf', 'SecDf'),
           loc='center right',title = 'visualization')
plt.show()

Upvotes: 0

Related Questions