如何在R中将30秒数据转为小时粒度并绘制全天热力图
解决30秒数据转60分钟粒度并绘制小时级温度热力图
步骤1:加载依赖包
先安装并加载数据处理与绘图所需的工具包:
install.packages("tidyverse") library(tidyverse)
步骤2:准备数据
这里模拟一份24小时、30秒间隔的温度数据,直接替换成你的真实数据即可:
set.seed(123) # 固定随机数保证结果可复现 dat <- tibble( datetime = seq(as.POSIXct("2024-01-01 00:00:00"), as.POSIXct("2024-01-01 23:59:30"), by = "30 sec"), temperature = rnorm(nrow(.), mean = 20, sd = 3) + sin(as.numeric(datetime - as.POSIXct("2024-01-01 00:00:00"))/3600*pi) * 5 )
步骤3:将30秒数据聚合为60分钟粒度
通过时间向下取整分组,计算每小时的温度统计量(这里用均值,可按需替换为最大值/最小值等):
dat_hourly <- dat %>% # 将时间向下取整到最近的60分钟 mutate(hour_interval = floor_date(datetime, unit = "60 minutes")) %>% group_by(hour_interval) %>% # 计算每小时的平均温度 summarize(avg_temperature = mean(temperature, na.rm = TRUE)) %>% ungroup()
步骤4:绘制热力图并调整X轴
核心解决点:
- 去除多余柱状图:放弃
geom_bar,改用geom_tile(热力图的标准几何对象) - 按小时设置X轴:用
scale_x_datetime(纯时间列用scale_x_time)自定义刻度与标签
ggplot(dat_hourly, aes(x = hour_interval, y = 1, fill = avg_temperature)) + # 绘制热力图瓷砖,白色边框区分小时区间 geom_tile(color = "white", size = 0.5) + # 设置温度颜色渐变 scale_fill_viridis_c(name = "平均温度(℃)", option = "plasma") + # 自定义X轴:按小时显示刻度与标签 scale_x_datetime( # 每小时设置一个刻度点 breaks = seq(as.POSIXct("2024-01-01 00:00:00"), as.POSIXct("2024-01-01 23:00:00"), by = "1 hour"), # 将刻度格式化为"HH:00"的小时格式 labels = function(x) format(x, "%H:00"), name = "时间(小时)" ) + # 隐藏无意义的Y轴 ylab("") + theme_minimal() + theme( axis.text.y = element_blank(), panel.grid = element_blank(), axis.title.y = element_blank() )
纯时间列(无日期)的scale_x_time用法
如果你的数据只有时分秒(如hms类型),可这样设置X轴:
# 先将datetime转换为纯时间列 dat_hourly <- dat_hourly %>% mutate(time_only = hms::as_hms(hour_interval)) ggplot(dat_hourly, aes(x = time_only, y = 1, fill = avg_temperature)) + geom_tile(color = "white", size = 0.5) + scale_fill_viridis_c(name = "平均温度(℃)") + scale_x_time( # 设置每小时一个刻度 breaks = hms::hms(seq(0, 82800, by = 3600)), # 格式化为小时标签 labels = function(x) str_remove(hms::format_hms(x), ":00$"), name = "时间(小时)" ) + theme_minimal() + theme(axis.text.y = element_blank())
内容的提问来源于stack exchange,提问作者Rstudent
相关产品推荐
相关产品推荐

