如何R中添加不同的趋势线?(How do I add different trend lines i

2019-07-20 14:09发布

我知道如何添加使用线性趋势线lmabline功能,但我怎么添加其他趋势线,如,对数,指数和电源趋势线?

Answer 1:

这里有一个我提前准备:

# 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)


Answer 2:

ggplot2使用方法stat_smooth ,使用相同的数据作为thelatemail

DF <- data.frame(x, y)



ggplot(DF, aes(x = x, y = y)) + geom_point() +
  stat_smooth(method = 'lm', aes(colour = 'linear'), se = FALSE) +
  stat_smooth(method = 'lm', formula = y ~ poly(x,2), aes(colour = 'polynomial'), se= FALSE) +
  stat_smooth(method = 'nls', formula = y ~ a * log(x) +b, aes(colour = 'logarithmic'), se = FALSE, start = list(a=1,b=1)) +
  stat_smooth(method = 'nls', formula = y ~ a*exp(b *x), aes(colour = 'Exponential'), se = FALSE, start = list(a=1,b=1)) +
  theme_bw() +
  scale_colour_brewer(name = 'Trendline', palette = 'Set2')

你也可以适应指数趋势线使用glm与日志链接功能

glm(y~x, data = DF, family = gaussian(link = 'log'))

对于一点乐趣,你可以使用theme_excel从ggthemes

library(ggthemes)
ggplot(DF, aes(x = x, y = y)) + geom_point() +
  stat_smooth(method = 'lm', aes(colour = 'linear'), se = FALSE) +
  stat_smooth(method = 'lm', formula = y ~ poly(x,2), aes(colour = 'polynomial'), se= FALSE) +
  stat_smooth(method = 'nls', formula = y ~ a * log(x) +b, aes(colour = 'logarithmic'), se = FALSE, start = list(a=1,b=1)) +
  stat_smooth(method = 'nls', formula = y ~ a*exp(b *x), aes(colour = 'Exponential'), se = FALSE, start = list(a=1,b=1)) +
  theme_excel() +
  scale_colour_excel(name = 'Trendline', palette = 'Set2')



文章来源: How do I add different trend lines in R?
标签: r trendline