Hi everyone,
I want to draw raw points and fitted lines (corresponding to a broken-line-plateau model which is an nls-object), both the points and the lines colored depending on a factor (group) values and splitted up in facets depending on another factor (sex) values.
The data and the code I've tested using ggplot() are provided below. The plot is just it should be, but showing the adjusted plateau model too.
I'm asking the comunity to help me, maybe using alternative code.
Thanks in advance
Mercè
# The data:
x <- c(rep(c(4.27,3.86,3.46,3.05,2.64),each=12))
sex <- c("b","g","g","b","g","b","g","b","b","g","g","b","g","b","g","b","b","g","g","g","g","b","b","b","b","g","g","b","b","b","g","g","b","g","b", "g","g","b","b","g","g","b","g","g","b","b","g","b","b","b","g","g","b","g","g","b","b","b","g","g")
group<-c("G","P","G","P","G","G","M","P","M","M","P","M","P","G","M","P","G","G","G","P","M","M","P","M","M","G","M","G","P","M","P","M","G","P","P","G","M","G","P","P","M","M","G","P","G","M","G","P","G","P","P","P","M","G","M","G","P","M","M","G")
y<-c(1063.2867,800.0000,829.0210,916.7832,958.3916,1016.6667,863.6364,902.4476,927.9720,910.8392,948.6014,982.5175,917.4242,980.4196,892.3077,897.9021,973.7762,861.1888,946.8531,708.0000,963.6364,855.2448,942.6573,953.4965,947.2028,936.3636,807.3427,972.7273,906.9930,917.8322,848.2517,824.8252, 1048.9510,774.1259,808.7121,951.7483,924.2424, 1020.2797,932.8671,834.9650,872.7273,905.9441,905.9441,879.0000,863.9860,945.1049,874.0000,837.4126,805.9441,825.8741,764.6853,684.9650,763.9860,859.4406,794.4056,892.6573,806.4394,883.2168,857.6923,974.8252)
dat<-data.frame(x,sex,group,y)
dat$x<-as.character(dat$x)
dat$sex<-as.factor(sex)
dat$group<-as.factor(dat$group)
# The model:
## broken line plateau for y with respect to x, with two block factors (sex and group)
model.nls_plat<-nls(y ~ ifelse(as.numeric(x) < 3.18, a + b *(3.18 - as.numeric(x)), a) + b1*(group=="M") + b2*(group=="G") + b3*(sex=="g"), data=dat, start = c(a=870, b=-150,b1=-47,b2=-90,b3=-51), trace = TRUE, control = list(maxiter=50))
summary(model.nls_plat)
pred.nls<-predict(model.nls_plat)
dat$pred.nls<-pred.nls
# the tested plot:
formula <- y ~ ifelse(as.numeric(x) < 3.18, a + b *(3.18 - as.numeric(x)), a) + b1*(group=="M") + b2*(group=="G") + b3*(sex=="g")
argum<- list(start=c(a=870, b=-150,b1=-47,b2=-90,b3=-51))
ggplot(dat, aes(x, y, fill = group)) +
geom_point(shape = 21, size = 3) +
xlab("x") +
ylab("y") +
geom_smooth(method = "nls", formula = formula, method.args = argum) +
facet_wrap(~sex, scales = "free_y")
# plateau lines are not visible !!