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

qmelpv7a  于 2023-07-31  发布在  Echarts
关注(0)|答案(1)|浏览(196)

如何在echarts4r线图中添加趋势线。在示例df中,我可以在ggplot2中添加red趋势线。我怎么能用echart4r做同样的事情?示例数据和代码如下。

# Required
library(Kendall)
library(zyp)
library(tidyverse)
library(echarts4r)

df <- structure(list(yr = c(1991, 1992, 1993, 1994, 1995, 1996, 1997, 
                      1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 
                      2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 
                      2020, 2021, 2022, 2023), val = c(-14.46, 9.92, -0.43, 0.22, -16.77, 
                                                       32.62, 6.78, -15.08, -5.26, 1.89, 3.17, -7.86, 3.55, -21.12, 
                                                       1.53, 2.57, 11.36, -9.24, -13.61, -10.89, -7.72, 6.53, 25.68, 
                                                       28.39, 12.06, -4.89, 4.51, -0.27, 4.65, -20.68, -8.02, 5.99, 
                                                       19.12)), row.names = c(NA, -33L), class = c("tbl_df", "tbl", 
                                                                                                   "data.frame"))

字符串

计算趋势和截距(MK),得到斜率和截距

trnd <- zyp.sen(val ~ yr, df)
df$trn <-  trnd$coeff[[2]]
df$incpt <-  trnd$coeff[[1]]
xs = c(min(df$yr), max(df$yr))
trn_slp = c(unique(df$incpt), unique(df$trn))
ys = cbind(1, xs) %*% trn_slp

使用ggplot2绘制趋势图。工作正常。

trnd_plt<-
  ggplot(data = df, aes(x = yr, y = val)) +
  geom_hline(yintercept = 0,
             color = "gray50",
             linewidth = 1) +
  geom_line(color = "blue", linewidth = 1) +
  geom_point(color = "blue", size = 2) +
  geom_segment(aes(
    x = xs[[1]],
    xend = xs[[2]],
    y = ys[[1]],
    yend = ys[[2]]
  ),
  color = "red",
  linewidth = 1)
trnd_plt

使用echarts4r绘图。

如何在这里添加带斜率和截距的红色趋势线?

df$yr_chr <- as.character(df$yr) # else echarts plot x-axis from 0 to 2500. 
df %>%
  e_charts(x = yr_chr) %>%
  e_line(serie = val, color="blue")%>% # add a line
  e_scatter(serie = val,color='blue')%>%
  e_legend(show = F) %>%
  e_tooltip() %>%
  e_theme("infographic") %>%
  e_title(text = "test Mann-Kendall trend plot ")

5us2dqdw

5us2dqdw1#

据我所知,没有直接的方法。我们必须计算趋势线的值。我们可以使用lm()来实现它:

# To calculate the values for the trend line

model <- lm(val ~ yr, data = df)

df$trendline <- model$coefficients[1] + model$coefficients[2] * df$yr

library(echarts4r)

df$yr_chr <- as.character(df$yr)

df %>%
  e_charts(x = yr_chr) %>%
  e_line(serie = val, name = "Original", symbol = 'circle', smooth = F) %>%
  e_line(serie = trendline, name = "Trendline", smooth = F) %>%
  e_legend(show = T) %>%
  e_tooltip() %>%
  e_theme("infographic") %>%
  e_title(text = "test Mann-Kendall trend plot with trendline")

字符串


的数据

相关问题