ggplot绘制y轴时间值:解决分类时间轴排序异常问题
问题:ggplot绘制Spaghetti图时y轴时间按字母排序而非时间顺序
我有一个名为data_clean的数据集,参与者10天内完成多轮survey。其中distress是分类变量,存储格式为「时:分」(如1:00、23:15)。用ggplot绘制Spaghetti图时,y轴时间按字母顺序排列,而非时间顺序,推测是因为变量为分类类型。
初始绘图代码
slopes_np<-ggplot(data = data_clean, aes(x=survey,y=distress, group=id, color=id))+ facet_wrap(~PP_rec)+ geom_smooth(method='lm', se=FALSE, size=0.5)+ xlab("Survey")+ylab("Distress")+ theme(legend.position = "none") slopes_np # 整体组的平滑线 smooth_nopoints <- slopes_np + stat_smooth(aes(group = 1), method = "lm", se = FALSE, colour="black", size=1) smooth_nopoints
尝试的无效方法(引入无关日期)
用as.POSIXct转换时间变量后,图表出现无关日期,不符合需求:
data_clean$distress_time <- as.POSIXct(data_clean$distress, format="%H:%M") class(data_clean$distress_time) theme_set(theme_bw(base_size = 7, base_family = "")) slopes_np<-ggplot(data = data_clean, aes(x=survey,y=distress_time, group=id, color=id))+ facet_wrap(~PP_rec)+ geom_smooth(method='lm', se=FALSE, size=0.5)+ xlab("Survey")+ylab("Distress")+ theme(legend.position = "none") slopes_np # 整体组的平滑线 smooth_nopoints <- slopes_np + stat_smooth(aes(group = 1), method = "lm", se = FALSE, colour="black", size=1) smooth_nopoints
需求:y轴仅显示按时间顺序排列的「时:分」格式(如0:00、1:00…23:00)。
示例数据
structure(list(id = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L), levels = c("400", "401", "402", "403", "404", "405", "406", "407", "408", "409", "411", "412", "413", "414", "415", "550", "551", "552", "553", "554", "555", "558", "559", "560", "561", "563", "565", "566", "567", "568", "569", "570", "571", "572", "573", "574", "575", "576", "577", "578", "580", "590", "591"), class = "factor"), distress = c("23:45", "23:30", "23:30", "23:45", "23:30", "22:30", "23:30", "21:30", "23:45", "22:45", "0:00", "1:00", "6:15", "0:00", "1:00", "0:00", "2:00", "2:00", "2:00", "1:45" ), survey = c(1, 4, 6, 9, 11, 1, 3, 5, 8, 11, 1, 4, 7, 9, 12, 1, 4, 7, 10, 12))) # PP_rec表示事件发生的前后
解决方案
推荐使用hms包处理时间,它专门用于存储时分秒类型,不会引入日期,且ggplot能自动识别时间顺序。
方法:使用hms类型变量自定义y轴格式
library(ggplot2) library(hms) # 将distress转换为hms类型(仅含时分秒,无日期) data_clean$distress_hms <- as_hms(data_clean$distress) # 绘制Spaghetti图 slopes_np <- ggplot(data = data_clean, aes(x = survey, y = distress_hms, group = id, color = id)) + facet_wrap(~PP_rec) + geom_smooth(method = 'lm', se = FALSE, size = 0.5) + # 自定义y轴显示格式为「时:分」 scale_y_time(format = "%H:%M") + xlab("Survey") + ylab("Distress") + theme(legend.position = "none") # 添加整体组的平滑线 smooth_nopoints <- slopes_np + stat_smooth(aes(group = 1), method = "lm", se = FALSE, colour = "black", size = 1) # 输出图表 smooth_nopoints
可选调整
如果需要y轴只显示整点刻度(如0:00、1:00…23:00),可以修改scale_y_time参数:
scale_y_time( format = "%H:%M", breaks = seq(hms(00, 00, 00), hms(23, 00, 00), by = "hour") )
内容的提问来源于stack exchange,提问作者o.y_80
相关产品推荐
相关产品推荐

