matplotlib second timeseries not plotting

Viewed 36

I want to plot two timeseries in the same plot, but the second plot is not shown properly. Sorry, I can't upload plots due to some limits.

Given two timeseries,

df1 = pd.DataFrame({
    'timestamp': [pd.Timestamp('2022-04-20 12:00:00'), 
                  pd.Timestamp('2022-04-20 13:00:00'), 
                  pd.Timestamp('2022-04-20 14:00:00')], 
    'value': [0, 1, 2]})

df2 = pd.DataFrame({
    'timestamp': [pd.Timestamp('2022-04-21 12:00:01'), 
                  pd.Timestamp('2022-04-21 13:00:01'),
                  pd.Timestamp('2022-04-21 14:00:01')], 
    'value': [0, 1, 2]})

If I plot df1 before df2, only df1 shows in the plot,

fig, ax = plt.subplots()
df1.plot(x='timestamp', y='value', figsize=(10, 5), ax=ax, label='df1')
df2.plot(x='timestamp', y='value', color='orange', ax=ax, label='df2')

Even if I specify xlim, df2 is not plotted,

fig, ax = plt.subplots()
xlim=(pd.Timestamp('2022-04-20 11:00:00'), pd.Timestamp('2022-04-21 15:00:00'))
df1.plot(x='timestamp', y='value', figsize=(10, 5), xlim=xlim, ax=ax, label='df1')
df2.plot(x='timestamp', y='value', color='orange', ax=ax, label='df2')

But if df2 is plotted before df1, everything works,

fig, ax = plt.subplots()
df2.plot(x='timestamp', y='value', color='orange', ax=ax, label='df2')
df1.plot(x='timestamp', y='value', figsize=(10, 5), ax=ax, label='df1')

I've figured out that it is caused by different schemas of timestamps. df1 is at X o'clock, but df2 is at X o'clock and 1 second. When I modified df2 to X o'clock, it works,

df2_new = pd.DataFrame({
    'timestamp': [pd.Timestamp('2022-04-21 12:00:00'), 
                  pd.Timestamp('2022-04-21 13:00:00'),
                  pd.Timestamp('2022-04-21 14:00:00')], 
    'value': [0, 1, 2]})

fig, ax = plt.subplots()
df1.plot(x='timestamp', y='value', figsize=(10, 5), ax=ax, label='df1')
df2_new.plot(x='timestamp', y='value', color='orange', ax=ax, label='df2_new')

How can I plot two timeseries properly without modifying data or manually adjusting their order? These timeseries are passed from outside with no limitation.


Edit:

In the first case (i.e. plot df1 before df2), if I apply plt.autoscale(), df2 is plotted at 1970s, while df1 is plotted at 2022.

fig, ax = plt.subplots()
df1.plot(x='timestamp', y='value', figsize=(10, 5), ax=ax, label='df1')
df2.plot(x='timestamp', y='value', color='orange', ax=ax, label='df2')
plt.autoscale()
1 Answers

I'm not sure but I think df.plot() overwrites the previous plot.

for Timestamp in df1.Timestamp:
    plt.plot(df1.Timestamp,df1.value)
    
for Timestamp in df1.Timestamp:
    plt.plot(df2.Timestamp,df2.value)

plt.show()
Related