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

如何使用ggplot2在数据点之间绘制弯曲的虚线?

实现ggplot2中数据点间的弯曲虚线

嘿,我明白你想要在数据点之间画出像Excel那样的弯曲虚线,这就来帮你搞定!先看看你现有代码里的几个小问题,然后给出具体的实现方案。

先修正原代码的基础问题

你当前的ggplot代码里有两处小错误:

  • aes()里的c(0, 0.16)是无效的,aes是用来映射数据列的,不能直接放常量范围
  • pch=17应该放在geom_point()里(如果你想显示数据点的话),而不是ggplot的全局aes中

接下来给你两种实现弯曲虚线的方法:


方法1:用geom_smooth生成平滑虚线(快速简单)

这个方法直接用ggplot的内置平滑函数生成弯曲的线,同时可以设置为虚线样式,还能保留数据点:

library(ggplot2)

Sample <- c(-1, -3, -5, -7, -9, -11, -13, -15, -17, -19, -21, -23, -25, -27, -29, -31, -33, -35, -37)
N <- c(0.14, 0.16, 0.09, 0.09, 0.11, 0.09, 0.10, 0.09, 0.11, 0.11, 0.09, 0.09, 0.05, 0.09, 0.09, 0.10, 0.11, 0.11, 0.11)
tab <- data.frame(N, Sample)

ggplot(tab, aes(x = N, y = Sample)) +
  # 先画数据点,形状用pch=17
  geom_point(pch = 17, color = "black") +
  # 生成平滑的弯曲虚线,method选loess适合小数据集,se=FALSE去掉置信区间
  geom_smooth(
    method = "loess", 
    formula = y ~ x,
    linetype = 3,  # 虚线样式
    color = '#2980B9', 
    se = FALSE,    # 关闭置信区间
    size = 0.8     # 线条粗细
  ) +
  theme_minimal() # 可选,美化主题

方法2:用样条插值生成自定义弯曲路径(更精准控制)

如果你想要完全贴合数据点的弯曲连接(类似Excel的“平滑线”),可以用样条插值生成更多中间点,再用geom_path画虚线:

library(ggplot2)
library(splines) # 需要加载这个包做样条插值

Sample <- c(-1, -3, -5, -7, -9, -11, -13, -15, -17, -19, -21, -23, -25, -27, -29, -31, -33, -35, -37)
N <- c(0.14, 0.16, 0.09, 0.09, 0.11, 0.09, 0.10, 0.09, 0.11, 0.11, 0.09, 0.09, 0.05, 0.09, 0.09, 0.10, 0.11, 0.11, 0.11)
tab <- data.frame(N, Sample)

# 用样条插值生成新的平滑数据点
spline_data <- data.frame(
  spline(
    x = tab$N, 
    y = tab$Sample, 
    n = 100 # 生成100个中间点,数值越大线条越平滑
  )
)

ggplot() +
  # 原始数据点
  geom_point(data = tab, aes(x = N, y = Sample), pch = 17, color = "black") +
  # 用插值后的点画弯曲虚线
  geom_path(
    data = spline_data, 
    aes(x = x, y = y), 
    linetype = 3, 
    color = '#2980B9', 
    size = 0.8
  ) +
  theme_minimal()

小提示

  • 如果你想让线条严格按照原始数据点的顺序连接,方法2里的spline默认是按x排序的,如果你需要保留原顺序,可以调整插值参数改用自然样条
  • 虚线样式linetype=3是标准虚线,你也可以用linetype="dashed"或者其他数值(1-6对应不同线型)来调整线条样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:11:55