拟合ggplot2中的指数衰减

时间:2015-12-07 20:57:13

标签: r ggplot2

根据书"非线性回归与R" 拟合非线性回归曲线如下:

y <- c(0.00000000,  0.00000000,  0.00000000,  0.07151853,  0.12230156, 0.12477607,  0.57459494, 0.71044407,0.77730922,  0.96877743,  1.00130198,  1.00690854,  1.19552293,  1.69514186,1.84095595,  1.93063711, 2.01310948,  2.35063440,  2.98573971,  3.09696917,3.23606040, 3.40477922,  3.42263648,  4.48309014,5.35996167,  5.58664330,  5.79808560, 5.86904909, 6.02004410,  7.71134227,  9.61312750, 10.34867252, 10.80706159, 10.96930945, 11.46816815,       13.21652574, 15.26685723, 19.33131681, 33.48608466, 65.84991001)

x<- c(0.000000000, 0.022094103, 0.007190170, 0.040666667, 0.241522350, 0.074884841, 0.010353894, 0.008258427, 0.030700869, 0.016620461, 0.012660429, 0.005000185, 0.006124385, 0.007464752, 0.035930910, 0.026537392,     0.006771706, 0.003332487, 0.005449347, 0.003840316, 0.003433708, 0.003220121, 0.002053425, 0.010153581, 0.004692195, 0.010461553, 0.005333333, 0.002056443, 0.002732524, 0.001395635, 0.001921910, 0.002827822,0.002577508, 0.004037920, 0.002791600, 0.001687790, 0.001047181, 0.000468419, 0.000652501, 0.000262411)

data<-as.data.frame(cbind(x,y))
head(data)
plot(y ~ x, data = data, xlab = "predictor",   ylab = "response",   ylim = c(0, 70))

expFct <- function(x, beta1, beta2,beta3) 
{exp(-beta1 * x)/(beta2 + beta3 * x) }
curve(expFct(x, beta1 = 1, beta2 = 0.01,
             beta3 = 40), add = TRUE, lty = 2)
model <- nls(y ~ expFct(x,beta1, beta2, beta3), data = data,
             start = list(beta1 = 1, beta2 = 0.01,
                          beta3 = 40))

但是,我需要使用ggplot2来拟合此曲线,但我没有成功。拜托,有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

这会有帮助吗

ggplot(data=data, aes(x=x, y=y)) + geom_smooth(method = "nls", formula = 'y ~ expFct(x,beta1, beta2, beta3)', 
   start=list(beta1=1,beta2=0.01,beta3=40),se = FALSE, linetype = 1, colour = "black") + xlab("predictor") + ylab("response") + geom_point(data=data, aes(x=x, y=y)) + theme_bw()

enter image description here

答案 1 :(得分:0)

您可以绘制数据,然后添加拟合值:

ggplot() +
  geom_point( data = data, aes(x = x, y = y) ) +
  geom_line( aes(x = x, y = fitted(model)) ) +
  labs( x = 'predictor', y = 'response' )

但是MLavoie答案是最好的,因为它将回归公式直接放在ggplot代码中。