在R中绘制显示日期的折线图

时间:2020-06-03 10:41:13

标签: r date plot time-series

我的数据如下所示:

Date           Time_finished
4/3/2020       16:30:21
4/6/2020       16:43:29
4/7/2020       16:28:47
4/8/2020       16:30:38
4/9/2020       16:50:01

我想绘制一个折线图,在x轴上显示日期,然后在y轴上完成时间,以显示时间序列图。由于某种原因,这似乎不起作用,将“日期”另存为“日期”,但将时间作为因素,是否还需要将其作为日期?

我尝试过正常情节,但没有运气。

谢谢

1 个答案:

答案 0 :(得分:3)

喜欢吗?

df <- tibble::tribble(
       ~Date, ~Time_finished,
  "4/3/2020",     "16:30:21",
  "4/6/2020",     "16:43:29",
  "4/7/2020",     "16:28:47",
  "4/8/2020",     "16:30:38",
  "4/9/2020",     "16:50:01"
  )

library(tidyverse)

df %>% 
  mutate(Date = as.POSIXct(Date, format = "%m/%d/%y"),
         Time_finished = as.POSIXct(Time_finished, format = "%H:%M:%S")) %>% 
  ggplot(aes(x = Date, y = Time_finished, group = 1)) +
  geom_line() + scale_y_datetime(breaks = date_breaks("10 min"),
                                 minor_breaks = date_breaks("2 min"),
                                 labels = date_format("%Hh %Mm %Ss"))

enter image description here