matplotlib Python:绘制时间增量

yeotifhr  于 2022-12-04  发布在  Python
关注(0)|答案(1)|浏览(157)

我有一个DataFrame,其中一列是时间,另一列存储了时滞。数据如下所示:

2020-04-18 14:00:00                         0 days 03:00:00
 2020-04-19 02:00:00                         1 days 13:00:00    
 2020-04-28 14:00:00                         1 days 17:00:00
 2020-04-29 20:00:00                         2 days 09:00:00
 2020-04-30 19:00:00                         2 days 11:00:00

Time, Length: 282, dtype: datetime64[ns]    Average time lag, Length: 116, dtype: object

我想绘制X轴上的时间与Y轴上的时间间隔。但是,绘制第二列时总是出错。有什么关于如何处理绘图数据的提示吗?

6ojccjat

6ojccjat1#

为了在Y轴上绘制时间间隔,您需要将时间间隔从timedelta对象转换为可在绘图中使用的数值。一种方法是使用total_seconds方法将时间间隔转换为秒,然后在Y轴上绘制结果值。
下面是一个如何执行此操作的示例:

import pandas as pd
import matplotlib.pyplot as plt

# Create a dataframe with the time and time lag data
data = [    ['2020-04-18 14:00:00', '0 days 03:00:00'],
    ['2020-04-19 02:00:00', '1 days 13:00:00'],
    ['2020-04-28 14:00:00', '1 days 17:00:00'],
    ['2020-04-29 20:00:00', '2 days 09:00:00'],
    ['2020-04-30 19:00:00', '2 days 11:00:00'],
]
df = pd.DataFrame(data, columns=['time', 'time_lag'])

# Convert the time and time lag columns to datetime and timedelta objects
df['time'] = pd.to_datetime(df['time'])
df['time_lag'] = pd.to_timedelta(df['time_lag'])

# Convert the time lag to seconds
df['time_lag_seconds'] = df['time_lag'].dt.total_seconds()

# Create a scatter plot with the time on the x-axis and the time lag in seconds on the y-axis
plt.scatter(df['time'], df['time_lag_seconds'])
plt.show()

相关问题