r - 如何在 R 中添加不同的趋势线?

标签 r trendline

我知道如何使用 lm 添加线性趋势线和 abline函数,但如何添加其他趋势线,例如对数、指数和幂趋势线?

最佳答案

这是我之前准备的一个:

# set the margins
tmpmar <- par("mar")
tmpmar[3] <- 0.5
par(mar=tmpmar)

# get underlying plot
x <- 1:10
y <- jitter(x^2)
plot(x, y, pch=20)

# basic straight line of fit
fit <- glm(y~x)
co <- coef(fit)
abline(fit, col="blue", lwd=2)

# exponential
f <- function(x,a,b) {a * exp(b * x)}
fit <- nls(y ~ f(x,a,b), start = c(a=1, b=1)) 
co <- coef(fit)
curve(f(x, a=co[1], b=co[2]), add = TRUE, col="green", lwd=2) 

# logarithmic
f <- function(x,a,b) {a * log(x) + b}
fit <- nls(y ~ f(x,a,b), start = c(a=1, b=1)) 
co <- coef(fit)
curve(f(x, a=co[1], b=co[2]), add = TRUE, col="orange", lwd=2) 

# polynomial
f <- function(x,a,b,d) {(a*x^2) + (b*x) + d}
fit <- nls(y ~ f(x,a,b,d), start = c(a=1, b=1, d=1)) 
co <- coef(fit)
curve(f(x, a=co[1], b=co[2], d=co[3]), add = TRUE, col="pink", lwd=2) 
添加描述性图例:
# legend
legend("topleft",
    legend=c("linear","exponential","logarithmic","polynomial"),
    col=c("blue","green","orange","pink"),
    lwd=2,
    )
结果:
enter image description here
绘制曲线的通用且不太长的方法是通过 x以及 curve 的系数列表功能,如:
curve(do.call(f, c(list(x), coef(fit)) ), add=TRUE)

关于r - 如何在 R 中添加不同的趋势线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15102254/

相关文章:

r - 在 Prolog 中使用嵌入式 R 工具

JavaScript图形趋势线(区域背景颜色)和颠倒的y轴

python - 为折线图绘制趋势线

statistics - Tableau、散点图和趋势线显示置信水平

python - Plotly Python 中的趋势线

python |绘制并拟合 (1/A)e^(-x/A) 形式的数据拟合,其中 A 是常数

r - 了解 base::identical() ——为什么是 "safer"?

r - ggpubr/ggbarplot 中的错误栏突然合并(没有更改代码),我怎样才能再次将它们分开?

r - 如何/何时在 R 中设置 HOME 环境变量

r - 为什么 RMarkdown 无法正确转义第二个 LaTeX 表?