ggplot2中如何调整时间轴时刻顺序,实现y轴时间围绕午夜居中?
要实现ggplot2绘图的y轴时间围绕午夜居中,可按照你的Time列的数据类型选择对应方案:
方案1:Time列为0~24的数值型数据
先对时间做映射转换,将12点之后的时间减24,让整体数值范围变为-12~12,0点刚好对应轴中心,再自定义y轴标签即可:
library(ggplot2) library(ggExtra) # 预处理:生成居中映射的时间列 LBB$mapped_time <- ifelse(LBB$Time > 12, LBB$Time - 24, LBB$Time) # 绘图 p <- ggplot(LBB, aes(x = RecordingDate, y = mapped_time)) + geom_point(size = .5) + scale_y_continuous( breaks = c(-12, -6, 0, 6, 12), labels = c("12:00", "18:00", "00:00", "06:00", "12:00"), name = "时间" ) + theme(legend.position="none") p2 <- ggMarginal(p, type = "density")
方案2:Time列为hms/POSIXct时间格式
直接通过scale_y_time设置轴范围为当日12点到次日12点,即可自动实现午夜居中:
library(ggplot2) library(ggExtra) library(hms) p <- ggplot(LBB, aes(x = RecordingDate, y = Time)) + geom_point(size = .5) + scale_y_time( limits = c(as_hms("12:00:00"), as_hms("36:00:00")), breaks = hms(c(12, 18, 24, 30, 36)*3600), labels = c("12:00", "18:00", "00:00", "06:00", "12:00"), name = "时间" ) + theme(legend.position="none") p2 <- ggMarginal(p, type = "density")
如果需要调整时间刻度密度,修改breaks和labels参数的取值即可。
内容的提问来源于stack exchange,提问作者elyse.mallinger
相关产品推荐
相关产品推荐

