将ggplot图表X轴标签替换为日期时间范围的实现方法
问题:将ggplot柱状图X轴数值标签替换为对应日期时间戳
数据集
DT Msc zdarzenie Sub Objetosc.norm 1 2022-01-12 18:00:00 1 1 11 22.9 2 2022-01-12 19:00:00 1 1 12 32.2 3 2022-01-12 20:00:00 1 1 13 24.9 4 2022-01-23 18:00:00 1 2 21 19.4 5 2022-01-23 19:00:00 1 2 22 33.8 6 2022-01-23 20:00:00 1 2 23 25.7 7 2022-01-24 19:00:00 1 3 31 20.9 8 2022-01-24 20:00:00 1 3 32 34.1 9 2022-01-24 21:00:00 1 3 33 25.8 10 2022-03-10 18:00:00 3 4 41 20.2 11 2022-03-10 19:00:00 3 4 42 32.1 12 2022-03-10 20:00:00 3 4 43 21.8 13 2022-04-03 19:00:00 4 5 51 19.0 14 2022-04-03 20:00:00 4 5 52 39.9 15 2022-04-03 21:00:00 4 5 53 26.3
现有绘图代码
ggplot(Kotl.gaz.sel.pyt) + geom_col(aes(x = Sub/10, y = Objetosc.norm, fill = factor(zdarzenie))) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5), legend.position = "none", legend.justification = "center") + facet_wrap(~Msc)
需求说明
当前图表X轴标签为Sub/10生成的数值,希望将其替换为对应分组的日期时间戳(每个zdarzenie分组对应一个日期,同时显示该分组内的时间范围信息)。
解决方案
方法1:预处理数据,自定义分组标签
先为每个zdarzenie分组生成包含日期和时间范围的标签,再将X轴映射为分组变量,替换标签内容:
library(dplyr) library(ggplot2) # 处理数据:提取日期、时间,生成分组标签 Kotl.gaz.sel.pyt <- Kotl.gaz.sel.pyt %>% mutate( date = as.Date(DT), time = format(DT, "%H:%M"), # 用zdarzenie作为分组ID group_id = zdarzenie, # 生成日期+时间范围的显示标签 group_label = paste(date, paste(min(time), max(time), sep = "-"), sep = "\n") ) %>% # 去重保留每个分组的唯一标签 distinct(group_id, group_label, .keep_all = TRUE) %>% right_join(Kotl.gaz.sel.pyt, by = names(Kotl.gaz.sel.pyt)) # 绘图 ggplot(Kotl.gaz.sel.pyt) + geom_col(aes(x = factor(group_id), y = Objetosc.norm, fill = factor(zdarzenie))) + scale_x_discrete(labels = ~ unique(Kotl.gaz.sel.pyt$group_label)[as.integer(.)]) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5), legend.position = "none", legend.justification = "center") + facet_wrap(~Msc)
方法2:直接映射时间变量,调整刻度
如果需要保留时间的连续性,直接将DT作为X轴变量,自定义刻度和标签:
ggplot(Kotl.gaz.sel.pyt) + geom_col(aes(x = DT, y = Objetosc.norm, fill = factor(zdarzenie))) + scale_x_datetime( # 取每个分组的第一个时间点作为刻度 breaks = ~ unique(Kotl.gaz.sel.pyt$DT[seq(1, nrow(Kotl.gaz.sel.pyt), 3)]), # 设置标签格式为日期+时间 labels = ~ format(., "%Y-%m-%d\n%H:%M") ) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5), legend.position = "none", legend.justification = "center") + facet_wrap(~Msc)
内容的提问来源于stack exchange,提问作者GrBa
相关产品推荐
相关产品推荐

