A. Bohyn
A. Bohyn

Reputation: 187

How to create a meanplot by group (gender analysis) using ggplot 2?

Okay, I'd like to create the following plot in R using ggplot2: Gender based meanplot

Here's the actual code to produce the output shown:

boxplot(mydata$socialanxiety~mydata$sex1,
+  horizontal=F, col = "gray", na.action=na.omit)

plotmeans(socialanxiety~sex1,xlab="Gender", ylab="Anxiety",
+ main="Mean Plot", data = mydata)
stripchart(mydata$socialanxiety~mydata$sex1,vertical=F,
+            xlab='Anxiety')
meanvec = tapply(mydata$socialanxiety,mydata$sex1,mean)
abline(h=1:2,lty=2,col="black")
points(meanvec,1:2, pch=17, col="red", cex=2)

Where mydata is a dataframe of observations with 3 columns:

Here is a code snippet to recreate some sample data.

n <- 100
mydata <- data.frame(socialanxiety=rnorm(n), 
       sex1=sample(c("male","female"),n,replace=T))

PS: these are fictional data.

Thank you in advance

Upvotes: 1

Views: 352

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24262

set.seed(1)
n <- 100
mydata <- data.frame(socialanxiety=rnorm(n), 
           sex1=sample(c(1,2),n,replace=T))

library(ggplot2)
ggplot(data=mydata, aes(x=sex1, y=socialanxiety)) +
 geom_point(pch=0, size=3) +
 stat_summary(fun.y = mean, color = "red", geom = "point", aes(group=sex1), size=5, pch=17)+
 geom_vline(aes(xintercept=as.numeric(sex1)), lty=2) + 
 scale_x_continuous(breaks=c(1,2), labels=c("F", "M")) +
 coord_flip() + theme_bw()

enter image description here

Upvotes: 1

Related Questions