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

如何在ggplot2散点图中添加跟随点位置的连线?

在ggplot2散点图中添加跟随点的连线

嗨,这个需求很容易实现!你只需要在已有的ggplot代码基础上,添加一个geom_line()图层,并且让它使用和散点图相同的x、y映射关系就可以了。

修改后的完整代码

library(ggplot2)
pl <- ggplot(df) + 
  geom_point(aes(x = Estación, y = pH)) +  # 原有的散点图层
  geom_line(aes(x = Estación, y = pH))     # 新增的连线图层
print(pl)

进阶:自定义连线样式

如果想要让连线和散点的视觉效果区分开,你还可以给geom_line()添加颜色、线型、粗细这类参数,比如:

library(ggplot2)
pl <- ggplot(df) + 
  geom_point(aes(x = Estación, y = pH), color = "#2c3e50", size = 3) +
  geom_line(aes(x = Estación, y = pH), color = "#e74c3c", linetype = "dashed", size = 1)
print(pl)

这样就能得到散点搭配跟随其位置连线的可视化图啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:27:06