追加回归线方程# 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)I have a simple dataset and I am trying to use the power trend to best fit the data. The sample data is very small and is as follows: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")Data looks as follows:> new Discharge Downstream Age1 250 0.3 1.32026242 300 0.3 1.08595143 500 0.3 0.63889924 700 0.3 0.45536465 900 0.3 0.3559352I tried to plot the above data using ggplot2 ggplot(new)+geom_point(aes(x=Discharge,y=Age))I could add the linear line using geom_smooth(method="lm") but I am not sure what code do I need to show the power line.The output is as follows:How Can I add a power linear regression line as done in excel ? The excel figure is shown below: 解决方案 Use nls (nonlinear least squares) as your smootheregggplot(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)Noting Doug Bates comments on R-squared values and non-linear models here, you could use the ideas inAdding Regression Line Equation and R2 on graphto append the regression line equation# 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中的功效回归与Excel相似的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 09:08
查看更多