ggplot2中geom_segment组件多余虚线问题求助
问题根源
你当前的geom_segment对所有行生成线段,当jumpTimes=0时,x = jumpTimes * time结果为0,对应的yend是当前累计的value,这就会在x=0处画出一条从(0,0)到(0, value)的垂直虚线,这就是多余的线条。同时你的geom_point也会在x=0处生成大量多余的点,因为大部分jumpTimes=0时x=0。
修正方案
只针对有跳跃(jumpTimes > 0)的时间点生成线段和点,过滤掉无跳跃的行即可解决问题。另外修正了标题中数学符号的渲染写法,确保希腊字母正常显示:
library(ggplot2) set.seed(42) # Parameters nSteps = 150 lambda = 0.1 # Intensity # Generate sample path of HPP and CPP jumpsHpp = rpois(nSteps, lambda) samplePath = data.frame(time = 1:nSteps, jumpTimes = jumpsHpp, gamma = rgamma(nSteps, shape = 20, rate = 1)) samplePath$value = cumsum(samplePath$gamma*samplePath$jumpTimes) # Create an origin new = data.frame( time = c(0, 1), jumpTimes = c(0, 0), gamma = c(0, 0), value = c(0, 0)) samplePath = rbind(new, samplePath[-1, , drop = FALSE]) # 过滤出有跳跃的事件 jump_events = subset(samplePath, jumpTimes > 0) # Create ggplot g1 = ggplot() + geom_step(data = samplePath, aes(x = time, y = value), size = 1, color = "red") + # 只在有跳跃的时间点画点 geom_point(data = jump_events, aes(x = time, y = -0.8), shape = "x", size = 3, color = "black") + # 只在有跳跃的时间点画虚线 geom_segment(data = jump_events, aes(x = time, xend = time, y = 0, yend = value), linetype = "dashed", color = "black") + coord_cartesian(clip = 'off') + labs(title = bquote(lambda == 0.1 ~ "" ~ alpha == 20 ~ " število korakov: 150"), x = "Čas", y = "Vrednost") print(g1)
内容的提问来源于stack exchange,提问作者VlakecTomaz
相关产品推荐
相关产品推荐

