ggplot2设置24小时时间轴边界 实现16:00至次日06:00连续展示
问题原因
你使用hms类时间作为x轴时,ggplot默认按照00:00到23:59的自然顺序排序,因此16:0023:00的观测会出现在x轴右侧,00:0006:00的观测出现在x轴左侧,x轴中心自然落在正午位置,无法实现夜间时段连续展示的需求。
你当前生成的默认效果图如下:
解决方法
给早于16:00的时间戳加86400秒(即24小时)调整排序逻辑,再手动设置x轴标签显示原始时间即可,完整可运行代码如下:
# 原始数据结构 wind_speed <- structure(list(time_start = structure(c(0, 3600, 7200, 10800, 14400, 18000, 21600, 57600, 61200, 64800, 68400, 72000, 75600, 79200, 82800), class = c("hms", "difftime"), units = "secs"), wind_avg = c(1.60133333333333, 1.54866666666667, 0.900666666666667, 1.28766666666667, 1.78533333333333, 0.678666666666667, 1.00733333333333, 0.531, 0.821666666666667, 0.119666666666667, 0.401333333333333, 0.501333333333333, 0.769333333333333, 1.797, 1.52266666666667 ), time_of_day = c("00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00")), row.names = c(NA, -15L), class = c("tbl_df", "tbl", "data.frame")) library(ggplot2) library(dplyr) # 调整时间顺序:早于16点的时间加24小时,保证16点到次日6点连续排序 wind_speed <- wind_speed %>% mutate(adjusted_time = as.numeric(time_start), adjusted_time = ifelse(adjusted_time < 16*3600, adjusted_time + 86400, adjusted_time)) # 绘图 ggplot(data = wind_speed, aes(x = adjusted_time, y = wind_avg)) + geom_point() + # 手动设置x轴刻度和标签,显示原始时间 scale_x_continuous( breaks = c(seq(16*3600, 23*3600, 3600), seq(24*3600, 30*3600, 3600)), labels = c(paste0(16:23, ":00"), paste0(0:6, ":00")), name = "时间" ) + ylab("平均风速")
如果不想额外加载dplyr包,也可以用base R完成时间调整:
wind_speed$adjusted_time <- as.numeric(wind_speed$time_start) wind_speed$adjusted_time[wind_speed$adjusted_time < 16*3600] <- wind_speed$adjusted_time[wind_speed$adjusted_time < 16*3600] + 86400
运行后x轴会按16:00→17:00→…→23:00→00:00→…→06:00的顺序排列,午夜00:00落在x轴中间位置,符合需求。
内容的提问来源于stack exchange,提问作者Susie Derkins
相关产品推荐
相关产品推荐

