r - 绘制没有日期的时间线
问题描述
我有一个二氧化碳传感器,可以在工作时间捕获浓度。现在我想创建一个线图,显示每个工作日随时间变化的一条线(从上午 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")
如何每天绘制一条线?
解决方案
在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()
推荐阅读
- c# - Azure DocumentDb API newtonsoft 解析器错误
- blueprism - 查询 Daily Utilization Summary 背后的数据
- javascript - Swift,使用 SwiftSoup 访问多个类以解析 HTML 文件
- android - 在 Android 4.4 及更高版本的服务中使用 Smsmanager 发送短信
- python - 气流无法从数据流中获取成功状态
- sql - 如何根据选择查询自定义列输出
- java - int[] 到 Hashset (Java)
- jquery - 如何将一组视频容器中的每个按钮与其视频相关联?
- hibernate - 使用 Hibernate 3.6.10 的 CriteriaQuery
- for-loop - SIMULINK:对工作区中数组的每个元素重复子系统并重新组合信号