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

如何在echarts4r R折线图中添加带斜率和截距的红色趋势线

在echarts4r中添加Mann-Kendall趋势线

要在echarts4r绘制的折线图中添加已知斜率和截距的红色趋势线,核心思路是手动计算趋势线对应每个x值的y值,再将其作为一个新系列叠加到图表中,具体步骤如下:

1. 准备数据与趋势参数

假设你已经通过Mann-Kendall方法得到了趋势线的slope(斜率)和intercept(截距),同时有示例数据df:

library(echarts4r)
library(Kendall)

# 示例数据
set.seed(123)
df <- data.frame(
  year = 2000:2020,
  value = rnorm(21, mean = 10, sd = 2) + 0.3*(2000:2020 - 2000)
)

# 模拟Mann-Kendall得到的趋势参数(实际替换为你的计算结果)
mk_result <- MannKendall(df$value)
slope <- 0.28
intercept <- 9.5

2. 计算趋势线数据

给原数据框添加趋势线的y值列,或者单独构造趋势线数据框:

# 方式1:直接在原数据框添加趋势线列
df$trend <- intercept + slope * df$year

# 方式2:单独构造趋势线数据框(不修改原数据)
trend_df <- data.frame(
  year = df$year,
  trend = intercept + slope * df$year
)

3. echarts4r绘制折线图+趋势线

方式1(基于修改后的原数据框)

df |>
  e_charts(x = year) |>
  # 绘制原始数据折线
  e_line(serie = value, name = "原始数据") |>
  # 绘制红色趋势线,设置线宽
  e_line(serie = trend, name = "趋势线", lineStyle = list(color = "red", width = 2)) |>
  e_tooltip(trigger = "axis") |>
  e_legend()

方式2(基于单独的趋势线数据框)

df |>
  e_charts(year) |>
  e_line(value, name = "原始数据") |>
  # 通过e_add添加趋势线数据系列
  e_add(trend_df, e_line(trend, name = "趋势线", lineStyle = list(color = "red", width = 2))) |>
  e_tooltip(trigger = "axis") |>
  e_legend()

关键说明

  • echarts4r没有类似ggplot2中geom_abline的直接函数,因此需要手动计算每个x对应的趋势y值,将其作为独立系列添加。
  • 若你的x轴是日期类型,需先将日期转换为数值型计算趋势y值,再转换回日期格式,确保坐标轴匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 16:52:51