我知道如何使用 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,
)
结果:绘制曲线的通用且不太长的方法是通过
x
以及 curve
的系数列表功能,如:curve(do.call(f, c(list(x), coef(fit)) ), add=TRUE)
关于r - 如何在 R 中添加不同的趋势线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15102254/