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

如何在R中结合geom_curve与gg_arrow实现变宽曲线路径箭头?

实现带渐变线宽的曲线箭头(结合ggarrow)

关于从geom_curve提取arc参数的说明

geom_curve基于贝塞尔曲线绘制,它没有直接输出"arc"相关的属性或数据。ggarrow的arc参数用于映射路径上每个点的线宽,因此无法从已绘制的geom_curve中提取该参数,需要提前生成包含路径点和对应线宽(arc)的数据框。

实现变宽曲线箭头的方案

我们可以手动生成贝塞尔曲线的路径点,同时为每个点指定线宽(arc),再用geom_arrow绘制。具体步骤如下:

  1. 安装并加载所需工具包:
install.packages(c("devtools", "bezier", "ggplot2"))
devtools::install_github("teunbrand/ggarrow")

library(ggarrow)
library(ggplot2)
library(bezier)
  1. 生成曲线路径点与线宽数据:
    参考geom_curve的参数逻辑,用bezier函数生成对应路径点,同时创建arc列定义线宽渐变规则:
# 定义基础曲线参数
df_curve <- data.frame(x1 = 120, x2 = 120, y1 = 40, y2 = 35, curvature = -0.2)

# 生成贝塞尔曲线控制点(匹配geom_curve的计算逻辑)
ctrl_points <- data.frame(
  x = c(df_curve$x1, 
        df_curve$x1 + df_curve$curvature * (df_curve$y2 - df_curve$y1),
        df_curve$x2),
  y = c(df_curve$y1,
        df_curve$y1 + df_curve$curvature * (df_curve$x1 - df_curve$x2),
        df_curve$y2)
)

# 生成路径点(n控制曲线精度)
n_points <- 100
curve_path <- bezier(t = seq(0, 1, length.out = n_points), p = ctrl_points)
curve_df <- data.frame(
  x = curve_path[,1],
  y = curve_path[,2],
  arc = seq(1, 0.2, length.out = n_points) # 设置线宽从1渐变到0.2
)
  1. 用geom_arrow绘制变宽曲线箭头:
ggplot() +
  geom_arrow(data = curve_df, aes(x = x, y = y, linewidth = arc),
             arrow = arrow(length = unit(0.05, "npc"))) +
  coord_cartesian(xlim = c(118, 122), ylim = c(34, 41)) # 适配曲线调整坐标范围

关键说明

  • arc参数直接映射路径上每个点的线宽,需要为路径的每个点指定对应值,才能实现渐变效果。
  • 贝塞尔控制点的计算逻辑与geom_curve保持一致,确保生成的曲线和原geom_curve绘制结果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:41:18