Home > Blockchain >  How to plot two different curves with different timestamps in Python?
How to plot two different curves with different timestamps in Python?

Time:08-31

For my research I did two experiments at a different time period. How can I plot two curves in one plot to see the difference between the curves? The timestamps are different (datetime is used for the x-axis), this makes it different to plot all the curves in one plot. I need to plot the orange curves in one plot.

First curve

Second curve

CodePudding user response:

A simple way of comparing this data would be to reindex your two dataframes such that their indices overlap and you can plot against them. I can't open the links to the data you provided so I created two dataframes myself. Each spans a different time period and has a different sample frequeny.

from datetime import datetime, timedelta
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


# Two time bases
t1 = np.arange(datetime(2022, 8, 25), datetime(2022, 8, 25, 5), timedelta(seconds=1)).astype(datetime)
t2 = np.arange(datetime(2022, 8, 29), datetime(2022, 8, 29, 7), timedelta(seconds=2)).astype(datetime)
enter code here

# Two dataframes, each with two measurements
df1 = pd.DataFrame(data={
    "measurement1": np.sin(0.001 * np.arange(0, len(t1))),
    "measurement2": np.cos(0.001 * np.arange(0, len(t1)))}, index=t1)
df2 = pd.DataFrame(data={
    "measurement1": np.sin(0.0015 * np.arange(0, len(t2))),
    "measurement2": np.cos(0.0015 * np.arange(0, len(t2)))}, index=t2)

Plotting them we can see it would be hard to compare if we use the datetime for the x-axis: hard to compare plot

To fix this you can create an index for each dataframe. Both indices will start at zero and terminate at the length of the largest dataframe, but they will have different step sizes:

index1 = np.arange(0, max(len(df1), len(df2)), step=max(len(df1), len(df2)) / len(df1))
index2 = np.arange(0, max(len(df1), len(df2)), step=max(len(df1), len(df2)) / len(df2))

# Set the new indices
df1 = df1.set_index(keys=index1)
df2 = df2.set_index(keys=index2)

Now plot:

plt.plot(df1.index, df1["measurement1"], label="m1, df1")
plt.plot(df1.index, df1["measurement2"], label="m2, df1")
plt.plot(df2.index, df2["measurement1"], label="m1, df2")
plt.plot(df2.index, df2["measurement2"], label="m2, df2")
plt.legend()

easy to compare plot

CodePudding user response:

Solution using twiny

import matplotlib.pyplot as plt
import numpy as np


x1l = np.linspace( 0, 6,150 )
s1 = np.sin( x1l )

x2l = np.linspace( 126, 132, 166 )
s2 = np.sin( x2l ) 

fig = plt.figure( )

ax=fig.add_subplot( 1, 1, 1 )
tx = ax.twiny()
ax.plot( x1l, s1, c="red" )
tx.plot( x2l, s2, c="blue" )

ax.tick_params(axis='x', colors='red')
tx.tick_params(axis='x', colors='blue')
plt.show()

Test for two sine curves with large time offset

  • Related