我知道如何使用lm
和abline
函数添加线性趋势线,但是如何添加其他趋势线,例如对数、指数和幂趋势线?
问问题
84730 次
2 回答
50
这是我之前准备的一个:
# 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)
于 2013-02-27T00:53:21.067 回答
23
一种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, method.args = list(start = list(a = 1, b = 1))) +
stat_smooth(method = 'nls', formula = y ~ a * exp(b * x), aes(colour = 'Exponential'), se = FALSE, method.args = list(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, method.args = list(start = list(a = 1, b = 1))) +
stat_smooth(method = 'nls', formula = y ~ a * exp(b * x), aes(colour = 'Exponential'), se = FALSE, method.args = list(start = list(a = 1, b = 1))) +
theme_excel() +
scale_colour_excel(name = 'Trendline')
于 2013-02-27T02:18:48.727 回答