【问题标题】:Combine similar rows to create a time series组合相似的行以创建时间序列
【发布时间】:2017-12-23 19:55:48
【问题描述】:

我正在尝试处理一些数据以使用 R 显示汽车的时间序列。我想绘制时间序列中每辆车的速度。我希望它看起来像下面的图像。每条线代表不同的汽车。

Cars    Date    Speed
Yellow Car  2017-07-02 17:41:00 20
Green car   2017-07-08 05:01:35 30
Yellow Car  2017-07-08 05:03:31 10
Blue Car    2017-07-08 05:52:55 4
Green car   2017-07-08 10:21:57 2
Green car   2017-07-08 12:07:51 12

期望的输出:

【问题讨论】:

    标签: r dataframe plot ggplot2


    【解决方案1】:

    您的数据集不完整,但您可以从下面的示例中了解:

    ggplot(df, aes(x=Time, y=Speed, group=Cars, color=Cars)) + geom_line() + 
                  scale_colour_manual(values=c("blue", "green", "yellow"))
    

    数据:

    这与您的数据不同(它有不同的列),但看起来很像。

    df <- structure(list(Cars = structure(c(3L, 2L, 3L, 1L, 2L, 1L), .Label = c("BlueCar", 
    "Greencar", "YellowCar"), class = "factor"), Date = structure(c(1L, 
    1L, 1L, 1L, 1L, 2L), .Label = c("2017-07-08", "207-07-08"), class = "factor"), 
    Time = structure(c(6L, 1L, 2L, 3L, 4L, 5L), .Label = c("05:01:35", 
    "05:03:31", "05:52:55", "10:21:57", "12:07:51", "17:41:00"
    ), class = "factor"), Speed = c(20L, 30L, 10L, 4L, 2L, 15L)),
    .Names = c("Cars", "Date", "Time", "Speed"), class = "data.frame", row.names = c(NA,-6L))
    

    【讨论】:

    • 老兄,这是很棒的帮助!另一个问题,如果我想在 x 轴内表示日期和时间怎么办。我偶然发现 as.POSIXlt 似乎采用这种 UTC 格式,我将如何在这里实现它?
    • @AnthonyM 添加这个+ scale_x_datetime(breaks = Date, labels = format(Date, "%Y-%m-%d %H:%M:%S")
    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2021-11-15
    • 2021-02-14
    相关资源
    最近更新 更多