【问题标题】:How to compare graphically two pandas dataframe where index is datetime如何以图形方式比较索引为日期时间的两个熊猫数据框
【发布时间】:2018-12-11 14:53:05
【问题描述】:

我正在测量温度数据,我得到这样的 .csv:

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

我想绘制在两个不同时间跨度内进行的两种相同类型的测量值。 那么我是否需要标准化日期时间或如何使它们在线条图中具有可比性? 感谢帮助。

【问题讨论】:

  • 通过减去合适的开始时间将索引改为timedelta

标签: pandas timeserieschart


【解决方案1】:

使用ax.twiny 创建独立轴

这是一种方法。假设您有以下数据框:

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)

您可以使用ax.twiny() 创建一个额外的 x 轴,这将创建一个共享 y 轴的双轴。这样您就可以在同一个图中拥有两个序列,并且不会丢失date 信息:

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

【讨论】:

  • 如果这对您有帮助,请不要忘记接受答案@lasse,谢谢!
【解决方案2】:

您的意思是在绘制比较值时要忽略时间戳?以下是如何在没有时间戳的情况下将两个时间序列绘制在一起。我添加了第二个随机温度列表。

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

【讨论】:

  • 谢谢。我想将时间保持为 x 轴。我找到了这个 pandas.Series.dt.normalize 但我不太确定它的作用。
猜你喜欢
  • 2021-05-03
  • 2013-07-20
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 2020-08-29
  • 2021-11-05
相关资源
最近更新 更多