Reputation: 11
I have fitted a nonlinear regression curve according to the book "Nonlinear regression with R" as follows:
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))
However, I need to fit this curve using ggplot2
and I was not successful. Please, can someone help me with this?
Upvotes: 1
Views: 3129
Reputation: 9836
Would this help answer the question?
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()
Upvotes: 3
Reputation: 1001
You can plot the data and then add the fitted values:
ggplot() +
geom_point( data = data, aes(x = x, y = y) ) +
geom_line( aes(x = x, y = fitted(model)) ) +
labs( x = 'predictor', y = 'response' )
But MLavoie answer is best, since it put the regression formula directly inside ggplot code.
Upvotes: 0