I am working on a logistic regression model with two continuous predictors. I want to present the results using ggplot2
and exploiting the facet_wrap
to show the regression lines using a categorical predictor with several levels. I know that I could use stat_smooth
to fit curves but my problem is that the relationship between my predictors differ according to groups and thus I have both significant linear and quadratic terms and even non-significant relationship. I write a function that allows me to fit the correct curve to my data but to each facet by time. But then how could i apply this using facet_wrap
and add the different regression lines (linear or quadratic) to each facet?
One example:
data <-data.frame (x=c(21.0,21.0,22.8,21.4,18.7,18.1,14.3,24.4,22.8, 19.2,17.8,16.4,17.3,15.2,10.4,10.4,14.7,32.4,30.4,33.9,21.5, 15.5,15.2,13.3,19.2,27.3,26.0,30.4,15.8,19.7,15.0,21.4),
y = c(160.0 ,160.0, 108.0 ,258.0 ,360.0 ,225.0 ,360.0 ,146.7 ,140.8, 167.6 ,167.6, 275.8 ,275.8, 275.8, 472.0 ,460.0 ,440.0 , 78.7 , 75.7, 71.1, 120.1 ,318.0 ,304.0,350.0,400.0,79.0,120.3,95.1,351.0,145.0,301.0,121.0), groups =c(6,6,4,6,8,6,8,4,4,6,6,8,8,8,8,8,8,4,4,4,4,8,8,8,8,4,4,4,8,6,8,4))
data.split <-split(data,groups)
ggplot2.function <- function(dat, x,y){
p1=ggplot(data=dat, aes(x=x, y=y)) +
geom_point()
m = glm(y~ poly(x,2), data = dat, family = "gaussian")
pvalue1= summary(m)$coef[, "Pr(>|t|)"] [2]
pvalue2= summary(m)$coef[, "Pr(>|t|)"] [3]
if(((pvalue2 > 0.05)==TRUE)&((pvalue1> 0.05)==TRUE)){
print(p1 )
}
if(((pvalue2 > 0.05)==TRUE)&((pvalue1< 0.05)==TRUE)){
print(p1 + stat_smooth(method = "glm", formula = y ~ x, size = 1,se=FALSE))
}
if((pvalue2 < 0.05)==TRUE){
print(p1 + stat_smooth(method = "glm", formula = y ~ poly(x, 2), size = 1, se=FALSE))
}
}
lapply(data.split,ggplot2.function)
Then i have three plots. First one with linear relationship, the second test is non-significant and the third one with quadratic relationship. Could i use the facet_wrap function in this case?. Any help will be highly appreciated. Thanks in advance.