You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:33:18