我有一个简单的数据集,我正在尝试使用幂趋势来最好地拟合数据。示例数据非常小,如下所示:

structure(list(Discharge = c(250, 300, 500, 700, 900), Downstream = c(0.3,
0.3, 0.3, 0.3, 0.3), Age = c(1.32026239202165, 1.08595138888889,
0.638899189814815, 0.455364583333333, 0.355935185185185)), .Names = c("Discharge",
"Downstream", "Age"), row.names = c(NA, 5L), class = "data.frame")

数据如下:
> new
  Discharge Downstream       Age
1       250        0.3 1.3202624
2       300        0.3 1.0859514
3       500        0.3 0.6388992
4       700        0.3 0.4553646
5       900        0.3 0.3559352

我试图使用ggplot2绘制上述数据
ggplot(new)+geom_point(aes(x=Discharge,y=Age))

我可以使用geom_smooth(method="lm")添加线性线,但是我不确定显示电源线需要使用什么代码。

输出如下:

如何像excel一样添加幂线性回归线? Excel图如下所示:

最佳答案

使用nls(非线性最小二乘法)作为平滑器

例如

ggplot(DD,aes(x = Discharge,y = Age)) +
  geom_point() +
  stat_smooth(method = 'nls', formula = 'y~a*x^b', start = list(a = 1,b=1),se=FALSE)

注意Doug Bates对R平方值和非线性模型here的评论,您可以在
Adding Regression Line Equation and R2 on graph

附加回归线方程
# note that you have to give it sensible starting values
# and I haven't worked out why the values passed to geom_smooth work!
power_eqn = function(df, start = list(a =300,b=1)){
  m = nls(Discharge ~ a*Age^b, start = start, data = df);
  eq <- substitute(italic(y) == a  ~italic(x)^b,
               list(a = format(coef(m)[1], digits = 2),
                    b = format(coef(m)[2], digits = 2)))
  as.character(as.expression(eq));
}

ggplot(DD,aes(x = Discharge,y = Age)) +
  geom_point() +
  stat_smooth(method = 'nls', formula = 'y~a*x^b', start = list(a = 1,b=1),se=FALSE) +
  geom_text(x = 600, y = 1, label = power_eqn(DD), parse = TRUE)

关于r - R中的功效回归与Excel相似,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18305852/

10-12 17:34
查看更多