Reputation: 79
I'm using ggplot to plot the below data, and I'm trying to fit a smoother that captures the gaussian-like nature of the curves. I've tried standard loess and spline smoothers, but they result in huge dips in the Front line that aren't there (I tried attaching an image of the stat_smooth() result, but I don't have 10 reputation points as I'm new to stackoverflow).
I'm now trying to force a gaussian smoother by creating a formula (MyFormula) that's a gaussian shape and using that in the stat_smooth function, but I get the following error, which I think is happening because the MyFormula equation isn't being separated by FrontBack:
"Error in model.frame.default(formula = C$mean_Dye ~ max(C$mean_Dye) + : variable lengths differ (found for 'max(C$mean_Dye)')"
Is there an easier way to fit a gaussian-shaped (or any other representative) smoother to this data for both the front and back lines?
MyFormula=C$mean_Dye~max(C$mean_Dye)*exp(-0.5*((C$Meters-mean(C$Meters))/sd(C$Meters))^2)
ggplot(C, aes(x=Meters, y=mean_Dye, color=FrontBack)) + geom_point(pch=19, size = 6, alpha=1/4) + geom_errorbar(aes(ymin=mean_Dye-seDye, ymax=mean_Dye+seDye), width=0.1) + coord_cartesian(ylim=c(-100,100), xlim=c(16,50)) + stat_smooth(method="gam", formula=MyFormula, group=C$FrontBack, se=F)
Meters mean_Dye seDye FrontBack
17.0 -0.005 0.05 Front
29.0 0.036 0.05 Front
31.5 50.78 14.3 Front
32.5 69.82 8.04 Front
33.0 58.53 5.72 Front
33.5 50.93 5.29 Front
34.5 43.15 3.70 Front
37.0 15.51 4.02 Front
49.0 0.069 0.03 Front
17.0 0.111 0.023 Back
23.0 1.92 0.278 Back
26.0 5.98 0.743 Back
28.0 12.13 1.186 Back
30.0 18.99 1.419 Back
31.0 19.04 0.916 Back
32.0 18.17 1.416 Back
33.0 16.51 2.143 Back
34.0 13.99 2.178 Back
35.0 11.85 2.136 Back
36.0 6.63 1.751 Back
38.0 0.97 0.689 Back
40.0 0.099 0.116 Back
43.0 0.004 0.039 Back
49.0 0.041 0.040 Back
Upvotes: 1
Views: 2070
Reputation: 79
Answer found in previous post - works great.
f<-function(x, theta) {
m<-theta[1]; s<-theta[2]; a<-theta[3]; b<-theta[4];
a*exp(-0.5*((x-m)/s)^2) + b
}
fit<-nls(y~f(x,c(m,s,a,b)), data.frame(x,y), start=list(m=12, s=5, a=12, b=-2))
Upvotes: 1