如何在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 ")
型
1条答案
按热度按时间5us2dqdw1#
据我所知,没有直接的方法。我们必须计算趋势线的值。我们可以使用
lm()
来实现它:字符串
的数据