如何移除ggplot中时序累积曲线的垂直下降线段
消除累积消耗图表中的垂直下降线段
问题场景
代码与图表展示了资源的周期性累积消耗(例如两户家庭的每日用电量),当前图表中存在陡峭的垂直下降线段,需要抑制该现象,推测day变量需在ggplot语句中发挥作用,但尝试多种方法未成功。
原始代码
ndays <- 3 readingsperday <- 10 timeofday <- 0:(-1+ndays*readingsperday)/readingsperday day <- trunc(timeofday) randu1 <-c( t(cbind( 0, matrix(runif( ndays*(-1+readingsperday)),nrow=ndays) ) ) ) randu2 <-c( t(cbind( 0, matrix(runif( ndays*(-1+readingsperday)),nrow=ndays) ) ) ) mytib <- tibble( time = 0:(-1+ndays*readingsperday)/readingsperday, day = trunc(time), randu1 , randu2 ) %>% group_by(day) %>% mutate(cumul1 = cumsum(randu1) ) %>% mutate(cumul2 = cumsum(randu2) ) %>% select(-c(randu1, randu2) ) %>% gather( `cumul1`, `cumul2`, value = 'value', key = 'meter' ) ggplot(mytib, aes(x=time, y=value, color=meter) ) + geom_line() + theme(legend.position="bottom")
原始图表

解决方案
问题根源是ggplot默认会将前一天累积值的终点与第二天累积值的起点连接,导致垂直下降线段。只需在aes()中添加分组参数,让线条仅在同一天同一电表的数据点间连接即可。
修改后的代码
ndays <- 3 readingsperday <- 10 timeofday <- 0:(-1+ndays*readingsperday)/readingsperday day <- trunc(timeofday) randu1 <-c( t(cbind( 0, matrix(runif( ndays*(-1+readingsperday)),nrow=ndays) ) ) ) randu2 <-c( t(cbind( 0, matrix(runif( ndays*(-1+readingsperday)),nrow=ndays) ) ) ) mytib <- tibble( time = 0:(-1+ndays*readingsperday)/readingsperday, day = trunc(time), randu1 , randu2 ) %>% group_by(day) %>% mutate(cumul1 = cumsum(randu1) ) %>% mutate(cumul2 = cumsum(randu2) ) %>% select(-c(randu1, randu2) ) %>% gather( `cumul1`, `cumul2`, value = 'value', key = 'meter' ) ggplot(mytib, aes(x=time, y=value, color=meter, group=interaction(day, meter)) ) + geom_line() + theme(legend.position="bottom")
关键解释
interaction(day, meter)会为每个日期与电表的组合生成唯一分组标识,确保ggplot仅在同一分组内的点之间绘制线条,避免跨天连接不同累积周期的数据点。- 也可以用
group=list(day, meter)替代,效果一致,但interaction()写法更简洁。
内容的提问来源于stack exchange,提问作者donman
相关产品推荐
相关产品推荐

