R语言ggplot2按日分面绘制Posture-Time散点图实现方法
你现在用facet_wrap分面的实现思路不需要拆分数据集就能满足需求,只需要调整分面变量、X轴映射逻辑和范围参数即可,具体实现如下:
核心问题修正
- 原有代码只提取了月内日号做分面变量,跨月/跨年时会把同号不同日期的数据混在同一个分面,且分面标题无法显示完整日期
- 直接用带完整日期的
Time字段映射X轴,无法统一给所有分面设置每日固定的8:00-17:00显示范围,轴标签会冗余显示日期信息
分面绘图实现代码
library(ggplot2) library(lubridate) library(scales) # 处理时间字段:提取每日的时分秒部分,统一映射到同一个虚拟日期的时间尺度,方便统一设置X轴范围 graph_pre <- graph_pre |> mutate(time_of_day = as.POSIXct(paste("2000-01-01", format(Time, "%H:%M:%S")))) ggplot(graph_pre, aes(x = time_of_day, y = Posture)) + geom_point(size = 1, alpha = 0.7) + # 按完整日期分面,自动生成带日期的分面标题,可通过ncol调整每行排列的图数量 facet_wrap( ~Date, ncol = 1, labeller = labeller(Date = function(x) paste0("Posture vs Time - ", x)) ) + # 固定X轴显示范围为每日8:00-17:00,按小时打刻度,标签只显示时分 scale_x_datetime( limits = c(as.POSIXct("2000-01-01 08:00:00"), as.POSIXct("2000-01-01 17:00:00")), breaks = date_breaks("1 hour"), labels = date_format("%H:%M") ) + labs(x = "Time", y = "Posture") + theme_bw()
单图单独导出方案
如果需要每日图表单独存为文件,再按日期拆分数据集循环绘图即可:
# 按日期拆分数据集 daily_dataset <- split(graph_pre, graph_pre$Date) # 循环生成每日图表并保存 for (current_date in names(daily_dataset)) { df <- daily_dataset[[current_date]] plot <- ggplot(df, aes(x = Time, y = Posture)) + geom_point(size = 1, alpha = 0.7) + scale_x_datetime( limits = c( as.POSIXct(paste(current_date, "08:00:00")), as.POSIXct(paste(current_date, "17:00:00")) ), breaks = date_breaks("1 hour"), labels = date_format("%H:%M") ) + labs( title = paste0("Posture vs Time - ", current_date), x = "Time", y = "Posture" ) + theme_bw() # 按日期命名保存图片,可自行调整宽高和分辨率 ggsave( filename = paste0("Posture_vs_Time_", current_date, ".png"), plot = plot, width = 10, height = 4, dpi = 300 ) }
内容的提问来源于stack exchange,提问作者Richard Michaud Langis
相关产品推荐
相关产品推荐

