Home > OS >  Plotting two pandas time-series on the same axes with matplotlib - unexpected behavior
Plotting two pandas time-series on the same axes with matplotlib - unexpected behavior

Time:10-12

I'm working with two timeseries (df1 and df2) and when I try to plot the on the same x-axis, with different y axis I get unexpected behavior.

Below the code and data.

dates1 = ['2021-08-26', '2021-08-27', '2021-08-30', '2021-08-31',
               '2021-09-01', '2021-09-02', '2021-09-03', '2021-09-07',
               '2021-09-08', '2021-09-09', '2021-09-10', '2021-09-13',
               '2021-09-14', '2021-09-15', '2021-09-16', '2021-09-17',
               '2021-09-20', '2021-09-21', '2021-09-22', '2021-09-23',
               '2021-09-24', '2021-09-27', '2021-09-28', '2021-09-29',
               '2021-09-30', '2021-10-01', '2021-10-04', '2021-10-05',
               '2021-10-06', '2021-10-07', '2021-10-08']


dates2 = ['2021-08-29', '2021-09-05', '2021-09-12', '2021-09-19',
               '2021-09-26']

y1 = np.random.randn(len(dates1)).cumsum()
y2 = np.random.randn(len(dates2)).cumsum()

df1 = pd.DataFrame({'date':pd.to_datetime(dates1), 'y1':y1})
df1.set_index('date', inplace=True)

df2 = pd.DataFrame({'date':pd.to_datetime(dates2), 'y2':y2})
df2.set_index('date', inplace=True)

When plotting the two datasets together either I see no plot (first plot) or I see the y data resampled in some way I don't understand (second plot). If I plot the data separately there is no issue (third & fourth plots).

fig, axs = plt.subplots(1,4, figsize=[12,4])

df1.plot(ax=axs[0])
df2.plot(ax=axs[0], secondary_y=True)

df2.plot(ax=axs[1])
df1.plot(ax=axs[1], secondary_y=True)

df1.y1.plot(ax=axs[2])
df2.y2.plot(ax=axs[3])

plt.tight_layout()

enter image description here

CodePudding user response:

  • enter image description here


    • Plotting with enter image description here

  • Related