matplotlib第二个时间序列未绘制



我想在同一图中绘制两个时间序列,但是第二个图没有正确显示。对不起,由于某些限制,我无法上传绘图。

给定两个时间序列,

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]})

如果我在df2之前绘制df1,则只有df1显示在图中,

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')

即使我指定xlim,df2也没有绘制,

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')

但如果df2df1之前绘制,则一切正常,

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')

我发现这是由不同的时间戳模式引起的。df1在X点,但df2在X点零1秒。当我修改df2到X点钟,它工作,

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')

如何在不修改数据或手动调整其顺序的情况下正确绘制两个时间序列?这些时间序列从外部传入,没有限制。

编辑:

在第一种情况下(即df1df2之前),如果我应用plt.autoscale(),df2绘制在1970年,而df1绘制在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()

我不确定,但我认为df.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()

最新更新