r - Fitting gaussian to data geom_point in ggplot2 -


i have following data set

structure(list(collimator = structure(c(1l, 1l, 1l, 1l, 1l, 1l,  1l, 1l, 1l, 1l, 1l, 1l, 1l, 2l, 2l, 2l, 2l, 2l, 2l, 2l, 2l, 2l,  2l, 2l, 2l, 2l), .label = c("n", "y"), class = "factor"), angle = c(0l,  15l, 30l, 45l, 60l, 75l, 90l, 105l, 120l, 135l, 150l, 165l, 180l,  0l, 15l, 30l, 45l, 60l, 75l, 90l, 105l, 120l, 135l, 150l, 165l,  180l), x1 = c(2099l, 11070l, 17273l, 21374l, 23555l, 23952l,  23811l, 21908l, 19747l, 17561l, 12668l, 6008l, 362l, 53l, 21l,  36l, 1418l, 6506l, 10922l, 12239l, 8727l, 4424l, 314l, 38l, 21l,  50l), x2 = c(2126l, 10934l, 17361l, 21301l, 23101l, 23968l, 23923l,  21940l, 19777l, 17458l, 12881l, 6051l, 323l, 40l, 34l, 46l, 1352l,  6569l, 10880l, 12534l, 8956l, 4418l, 344l, 58l, 24l, 68l), x3 = c(2074l,  11109l, 17377l, 21399l, 23159l, 23861l, 23739l, 21910l, 20088l,  17445l, 12733l, 6046l, 317l, 45l, 26l, 46l, 1432l, 6495l, 10862l,  12300l, 8720l, 4343l, 343l, 38l, 34l, 60l), average = c(2099.6666666667,  11037.6666666667, 17337, 21358, 23271.6666666667, 23927, 23824.3333333333,  21919.3333333333, 19870.6666666667, 17488, 12760.6666666667,  6035, 334, 46, 27, 42.6666666667, 1400.6666666667, 6523.3333333333,  10888, 12357.6666666667, 8801, 4395, 333.6666666667, 44.6666666667,  26.3333333333, 59.3333333333)), .names = c("collimator", "angle",  "x1", "x2", "x3", "average"), row.names = c(na, -26l), class = "data.frame") 

i first scale average counts both collimator y , n make highest counts 1

df <- ddply(df, .(collimator), transform,             norm.average = average / max(average)) 

and plot curves:

ggplot(df, aes(x=angle,y=norm.average,col=collimator)) +    geom_point() + geom_line() 

using geom_line quite unpleasing on eye , rather fit data using stat_smooth. each data set should symmetric mean think gaussian fit should ideal. how can fit gaussian dataset collimator="y" , collimator="n" in ggplot2 or using base r. output mean , standard deviation. can done?

by definition data not gaussian kind of gaussian-like shape, , here example of visualization of fitting:

fit <- dlply(df, .(collimator), function(x) {     co <- coef(nls(norm.average ~ exp(-(angle - m)^2/(2 * s^2)), data = x, start = list(s = 50, m = 80)))     stat_function(fun = function(x) exp(-(x - co["m"])^2/(2 * co["s"]^2)), data = x) })  ggplot(df, aes(x = angle, y = norm.average, col = collimator)) + geom_point() + fit 

enter image description here


updated

to obtain parameters:

fit <- dlply(df, .(collimator), function(x) {     co <- coef(nls(norm.average ~ exp(-(angle - m)^2/(2 * s^2)), data = x, start = list(s = 50, m = 80)))     r <- stat_function(fun = function(x) exp(-(x - co["m"])^2/(2 * co["s"]^2)), data = x)     attr(r, ".coef") <- co     r }) 

then,

> ldply(fit, attr, ".co")   collimator        s        m 1          n 52.99117 82.60820 2          y 21.99518 86.61268 

Comments