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

ggplot使用geom_path搭配scale_size_manual消除分段连接间隙的方法

解决方法

最简单的实现方式是在原有路径图层下方新增一层无分组、统一使用最大线宽的底线路径,自动填充所有分段连接处的间隙,无需手动处理端点:

修改后的绘图代码如下:

plo <- ggplot() +
  # 新增底层:完整无断点的粗线,填充间隙
  geom_path(data = dat, aes(x = x, y = y), size = 1.5) +
  # 原有分层控制粗细的路径
  geom_path(data = dat, 
            aes(x = x, y = y, size = if_else(p == 0, "A", "B"), group = s)) +
  scale_size_manual(name = NULL, values = c("A" = 0.3, "B" = 1.5)) +
  # 以下元素仅用于说明问题
  geom_point(aes(x = (dat$x[5] + dat$x[6]) / 2, y = (dat$y[5] + dat$y[6]) / 2), shape = 1, color = "blue", size = 8) +
  geom_point(aes(x = (dat$x[48] + dat$x[49]) / 2, y = (dat$y[48] + dat$y[49]) / 2), shape = 1, color = "blue", size = 8) +
  geom_point(aes(x = (dat$x[61] + dat$x[62]) / 2, y = (dat$y[61] + dat$y[62]) / 2), shape = 1, color = "blue", size = 8) +
  coord_fixed() + theme_bw()
plo

如果希望连接处显示为细线,只要把底层的线宽改成细线值0.3即可,逻辑完全一致。


内容的提问来源于stack exchange,提问作者Rumpl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:36:06