首页 > 解决方案 > 绘制没有日期的时间线

问题描述

我有一个二氧化碳传感器,可以在工作时间捕获浓度。现在我想创建一个线图,显示每个工作日随时间变化的一条线(从上午 8 点到下午 6 点)。

一些样本数据:

co2data <- data.frame(
  dateTime = c(
    "2021-08-18 08:00:00",
    "2021-08-18 09:00:00",
    "2021-08-18 10:00:00",
    "2021-08-18 11:00:00",
    "2021-08-18 12:00:00",
    "2021-08-18 13:00:00",
    "2021-08-18 14:00:00",
    "2021-08-18 15:00:00",
    "2021-08-18 16:00:00",
    "2021-08-18 17:00:00",
    "2021-08-18 18:00:00",
    "2021-08-19 08:00:00",
    "2021-08-19 09:00:00",
    "2021-08-19 10:00:00",
    "2021-08-19 11:00:00",
    "2021-08-19 12:00:00",
    "2021-08-19 13:00:00",
    "2021-08-19 14:00:00",
    "2021-08-19 15:00:00",
    "2021-08-19 16:00:00",
    "2021-08-19 17:00:00",
    "2021-08-19 18:00:00"
    
  ),
  ppm = c(
    400,
    450,
    456,
    560,
    670,
    690,
    810,
    900,
    600,
    650,
    700,
  
    410,
    470,
    480,
    590,
    700,
    710,
    810,
    900,
    1010,
    1000,
    1100 
    
  )
)

现在我可以绘制浓度随时间的变化,但我不知道如何仅在 x 轴上绘制时间(无日期)。

co2data <- co2data %>% mutate(dateTime = as.POSIXct(dateTime))

co2data %>%
  ggplot(aes(x = dateTime, y = ppm)) + 
  geom_line() +
  labs(title = "CO2-Concentration", y = "CO2-concentration ppm", x = "Time")

如何每天绘制一条线?

标签: rggplot2dplyrtidyverse

解决方案


data.table包(或 lubridate)的帮助下,您可以从日期/时间字符串中提取时间信息。

require(data.table)
require(ggplot2)

setDT(co2data)

co2data[ , time := hour(as.ITime(dateTime)) ]
co2data[ , yday := as.factor(yday(as.IDate(dateTime))) ]

ggplot(co2data, aes(x = time, y = ppm, col = yday)) +
  geom_line() +
  labs(title = "CO2-Concentration", y = "CO2-concentration ppm", x = "Time") +
  theme_bw()

推荐阅读