如何调整ggplot图表X轴时间顺序,使午夜00:00居中?
调整ggplot2柱状图X轴,将午夜(00:00)置于中心
我用以下代码生成了柱状图:
ggplot(MAGS)+ geom_col(aes(x = Photo.time@hour + Photo.time@minute/60, y = Number.of.Animals), lwd = 1) + ylab("total amount") + scale_x_continuous(breaks = seq(0,24,4), name = "time", labels = c( "0:00", "4:00", "8:00", "12:00", "16:00", "20:00", "23:59")) + theme_bw() + theme_classic() scale_y_continuous(breaks = seq(0,10,2), name = "total amount", labels = c( "0","2","4","6","8","10"))
当前图表可用,但我需要调整X轴顺序:从12:00pm开始,把00:00am放在X轴中间,最后以11:59am结束(相当于原顺序反转)。因为数据集来自夜行性动物,午夜是活动高峰,这样的布局更合理。我尝试了多种方法都没成功,希望得到帮助。
当前图表效果:
解决思路
核心是转换时间变量,将中午12点后的时间数值减去24,让X轴范围变为-12到12,这样0点(午夜)自然处于中心位置,再对应调整轴刻度和标签即可。
修改后的代码
# 先处理时间变量:把12:00及之后的时间减去24 MAGS <- MAGS %>% mutate(adjusted_time = ifelse(Photo.time@hour >= 12, Photo.time@hour + Photo.time@minute/60 - 24, Photo.time@hour + Photo.time@minute/60)) # 绘制调整后的图表 ggplot(MAGS)+ geom_col(aes(x = adjusted_time, y = Number.of.Animals), lwd = 1) + ylab("total amount") + # 调整X轴刻度:对应-12到12,间隔4小时,标签按需求设置 scale_x_continuous(breaks = seq(-12, 12, 4), name = "time", labels = c("12:00", "16:00", "20:00", "0:00", "4:00", "8:00", "11:59")) + scale_y_continuous(breaks = seq(0,10,2), name = "total amount", labels = c("0","2","4","6","8","10")) + theme_classic()
补充说明
如果你的Photo.time是POSIXct类,推荐用lubridate包的函数来更简洁提取时间:
library(lubridate) MAGS <- MAGS %>% mutate(adjusted_time = ifelse(hour(Photo.time) >= 12, hour(Photo.time) + minute(Photo.time)/60 - 24, hour(Photo.time) + minute(Photo.time)/60))
内容的提问来源于stack exchange,提问作者Eliomys
相关产品推荐
相关产品推荐

