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

如何控制ggalt包geom_xspline函数的过度曲率问题

解决geom_xspline过度曲率与顶点贴合问题

问题根源

  1. 多余的抖动设置:position = position_jitter()会让线条位置随机偏移,加剧数据点与曲线的错位
  2. spline_shape参数不合理:-0.5的曲率过大,导致曲线在峰值点处过度弯曲,使顶点落在曲线下方;调至-0.2又会丢失平滑感

解决方案

方案1:使用单调样条(推荐)

单调样条能保证曲线严格遵循数据的增减趋势,所有极值点(如2019年的26.9%)都会精准落在曲线上,同时保持平滑效果。使用stat_smooth配合method = "monoH.FC"实现:

library(ggplot2)

AÑO <- seq(2004,2023, by = 1)
No_ejecutado <- c(10.2 , 5.2, 5.4 , 4.0 , 6.6 , 3.8 , 4.1, 15.3, 11.1, 12.1 ,10.1, 12.9 ,19.8, 17.2 ,22.4 ,26.1 ,26.9 , 9.3,
                  8.7 ,7.3 )

Congreso_12 <- data.frame(AÑO,No_ejecutado)

no_ejecucion <- ggplot(Congreso_12, aes(AÑO, No_ejecutado, group = 1)) +
  # 单调样条曲线,确保峰值精准贴合
  stat_smooth(method = "monoH.FC", formula = y ~ x, color = "#2FC1D3", linewidth = 1.5, se = FALSE) +
  geom_point( 
    fill ="#2FC1D3", 
    size = 4, 
    pch = 21,
    color = "white", 
    stroke = 1
  ) +
  scale_x_continuous(breaks = seq(2004,2023,by = 1)) +
  geom_text(
    aes(label = paste0(round(No_ejecutado,3),"%")),
    family = "avenir",
    fontface = "bold",
    size = 4,
    nudge_y = 0.4
  )

no_ejecucion

方案2:优化geom_xspline参数

如果坚持使用geom_xspline,调整spline_shape到-0.3~-0.4区间,同时移除position_jitter(),平衡平滑度与贴合度:

library(ggalt)
library(ggplot2)

AÑO <- seq(2004,2023, by = 1)
No_ejecutado <- c(10.2 , 5.2, 5.4 , 4.0 , 6.6 , 3.8 , 4.1, 15.3, 11.1, 12.1 ,10.1, 12.9 ,19.8, 17.2 ,22.4 ,26.1 ,26.9 , 9.3,
                  8.7 ,7.3 )

Congreso_12 <- data.frame(AÑO,No_ejecutado)

no_ejecucion <- ggplot(Congreso_12, aes(AÑO, No_ejecutado, group = 1)) +
  geom_xspline(spline_shape = -0.35, color = "#2FC1D3", linewidth = 1.5) + # 移除抖动,微调曲率
  geom_point( 
    fill ="#2FC1D3", 
    size = 4, 
    pch = 21,
    color = "white", 
    stroke = 1
  ) +
  scale_x_continuous(breaks = seq(2004,2023,by = 1)) +
  geom_text(
    aes(label = paste0(round(No_ejecutado,3),"%")),
    family = "avenir",
    fontface = "bold",
    size = 4,
    nudge_y = 0.4
  )

no_ejecucion

效果说明

  • 方案1的单调样条完全避免了曲线越过数据点的问题,适合需要精准展示极值的场景
  • 方案2的优化参数能让曲线贴近所有数据点,同时保持自然的平滑感,不会出现生硬的方形转折

内容的提问来源于stack exchange,提问作者Teco Jesús

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 17:17:41