R语言绘图:如何将时间序列x轴缩放为0-100%区间绘制分组折线图
实现x轴0-100%归一化的方法
你需要对每个测量组的时间做最大最小归一化,将不同时间范围的序列统一拉伸到0-100的区间,具体实现代码如下:
library(tidyverse) # 原始数据构造 measurement <- c("first", "second", "third", "fourth") group <- c("A", "B", "A", "B") time_1 <- c("1", "2", "1", NA) time_2 <- c(NA, "3", NA, "4") time_3 <- c("10", "15", "17", "19") time_4 <- c("5", NA, "8", NA) time_5 <- c("1", "2", "1", "1") time_6 <- c("3", NA, NA, NA) time_7 <- c("4", NA, NA, NA) time_8 <- c("2", NA, NA, NA) test_plot <- data.frame(measurement, group, time_1, time_2, time_3, time_4, time_5, time_6, time_7, time_8) # 数据预处理 gather_testplot <- test_plot %>% # 转换为长表 pivot_longer(cols = starts_with("time_"), names_to = "time", values_to = "value") %>% # 清理空值 drop_na(value) %>% # 转换字段类型 mutate( time = as.numeric(str_remove(time, "time_")), value = as.numeric(value) ) %>% # 按单条测量序列分组,可根据实际业务调整分组字段 group_by(group, measurement) %>% mutate( # 最大最小归一化到0-100范围 norm_time = (time - min(time))/(max(time) - min(time)) * 100 ) %>% ungroup() # 绘图 ggplot(gather_testplot, aes(x=norm_time, y=value, color=group, group=interaction(group, measurement))) + geom_line() + # x轴添加百分号标识 scale_x_continuous(labels = function(x) paste0(x, "%"), name = "时间进度")
核心逻辑说明
- 归一化计算默认按「group+测量批次」分组处理,如果你同一个group下的所有测量属于同一时间序列,只保留
group作为group_by的唯一字段即可。 - 如果你的数据存在单条序列只有1个时间点的情况,可以额外加条件判断避免分母为0的报错。
- 最终x轴数值统一为0-100,对应测量进度的0%到100%,不同耗时的序列会均匀分布在x轴区间内。
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

