I am trying to do a nls fit with ggplot with the following data:
df <- data.frame(t = 0:30, m = c(125.000000, 100.248858, 70.000000, 83.470795, 100.000000, 65.907870, 66.533715, 53.588087, 61.332351, 43.927435, 40.295448, 44.713459, 32.533143, 36.640336, 40.154711, 23.080295, 39.867928, 22.849786, 35.014645, 17.977267, 21.159180, 27.998273, 21.885735, 14.273962, 13.665969, 11.816435, 25.189016, 8.195644, 17.191337, 24.283354, 17.722776)
The code I have so far (a bit simplified) is
ggplot(df, aes(x = t, y = m)) +
geom_point() +
geom_smooth(method = "nls", formula=log(y)~x)
But I get the following error
Error in cll[[1L]] : object of type 'symbol' is not subsettable
I have browsed stackoverflow and found similar issues, but I have not been able to solve the problem. I would really like to plot the data without transforming the axis.
Any help is much appreciated.
For nls
you have to specify the parameters more carefully. Also, you probably don't want to use log(y)
, because that will plot the logarithm instead of y
. My guess is that you want to use something like y ~ exp(a + b * x)
. See below for an example.
ggplot(df, aes(x = t, y = m))+
geom_point()+
geom_smooth(method = "nls", formula = y ~ exp(a + b * x), start=list(a=0, b=1), se=FALSE)
You could also use glm
instead of nls
. For instance the following gives you the same solution.
ggplot(df, aes(x = t, y = m))+
geom_point()+
geom_smooth(method = "glm", formula = y ~ x, family=gaussian(link = "log"), se=FALSE)