如何在R中添加不同的趋势线? [英] How do I add different trend lines in R?

查看:932
本文介绍了如何在R中添加不同的趋势线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know how to add a linear trend line using the lm and abline functions, but how do I add other trend lines, such as, logarithmic, exponential, and power trend lines?

推荐答案

这是我之前准备的:

# 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函数,例如:

A generic and less long-hand way of plotting the curves is to just pass x and the list of coefficients to the curve function, like:

curve(do.call(f,c(list(x),coef(fit))),add=TRUE)

这篇关于如何在R中添加不同的趋势线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆