0

我正在尝试将数据显示到一个带有两条迹线的折线图中,其中x 轴上的时间从 00:00:00 到 23:59:59,在y 轴上为 “down_speed”,并且每条迹线都将显示一天的数据。例如从 4 月 27 日开始的 Trace1 (00:43:02, 03:43:30, 08:44:13, 18:01:12, 23:32:02) 和从 4 月 28 日开始的 Trace2 (03:02:29, 09 :03:07、18:03:56、23:04:40)。

我有 csv,其中数据存储并按时间排序,如下所示:

    id             time         down_speed  
     1    2020-04-27 00:43:02     4,807  
     2    2020-04-27 03:43:30     5,046  
     3    2020-04-27 08:44:13     2,12  
     4    2020-04-27 18:01:12     4,065  
     5    2020-04-27 23:32:02     4,558  
     6    2020-04-28 03:02:29     4,803
     7    2020-04-28 09:03:07     3,967
     8    2020-04-28 18:03:56     3,617
     9    2020-04-28 23:04:40     5,703

现在我有这段代码,它是从两个确切时间点的范围中选择的,但我不知道如何分隔日期,然后将它们放在同一个“x”轴上的一个图表中,显示从午夜到午夜的全天。

import pandas as pd
import plotly.express as px
import plotly.offline as py

df  = pd.read_csv('my_file.csv',parse_dates=['time']);

#plot all data between two times
mask = (df['time'] > '2020-04-27 00:00:00') & (df['time'] <= '2020-04-27 23:59:59')
fig = px.line(df.loc[mask], x = 'time', y = 'speed_download')
py.plot(fig)

我正在阅读熊猫时间序列的文档,但我没有找到任何可行的方法,在我开始做一些蛮力解决方案之前有什么想法吗?

4

1 回答 1

0
import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({'time': {1: '2020-04-27 00:43:02', 2: '2020-04-27 03:43:30', 3: '2020-04-27 08:44:13', 4: '2020-04-27 18:01:12', 5: '2020-04-27 23:32:02', 6: '2020-04-28 03:02:29', 7: '2020-04-28 09:03:07', 8: '2020-04-28 18:03:56', 9: '2020-04-28 23:04:40'},
                   'down_speed': {1: 4807, 2: 5046, 3: 2120, 4: 4065, 5: 4558, 6: 4803, 7: 3967, 8: 3617, 9: 5703}})

df['date'] = pd.to_datetime(df['time']).dt.date
df['time'] = pd.to_datetime(df['time']).apply(lambda x: x.replace(year=1990, month=1, day=1))

# extract the list of dates
dates = list(df['date'].sort_values().unique())

# generate the traces for the first date
df1 = df[df['date'] == dates[0]]

data = [go.Scatter(x=list(df1['time']),
                   y=list(df1['down_speed']),
                   name=str(dates[0]),
                   mode='markers+lines')]

# add the traces for the subsequent dates
for date in dates[1:]:

    df1 = df[df['date'] == date]

    data.append(go.Scatter(x=list(df1['time']),
                           y=list(df1['down_speed']),
                           name=str(date),
                           mode='markers+lines'))

# define the figure layout
layout = dict(xaxis=dict(range=[df1['time'].min(), df1['time'].max()],
                         tickformat='%H:%M:%S',
                         type='date',
                         autorange=False))

fig = go.Figure(data=data, layout=layout)

fig.show()

在此处输入图像描述

于 2020-04-29T06:12:26.403 回答