Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add the mean line to grouped density plot in R?

I am trying to draw a grouped density plot and add the mean line of each plot; here is the code


data <- data.frame(
 Accuracy=abs(rnorm(140)),
Species=c(rep("A.All",20),rep("B. double",60),rep("C.single",60),
          rep("D.All",20),rep("E.double",60),rep("F.single",60)),

Modality=c(rep("All,w0",10),rep("double1,w0",10),rep("double2,w0",10),rep("double3,w0",10),
          rep("single1,w0",10),rep("single2,w0",10),rep("single3,w0",10),
          rep("All,w2",10),rep("double1,w2",10),rep("double2,w2",10),rep("double3,w2",10),
          rep("single1,w2",10),rep("single2,w2",10),rep("single3,w2",10))
)


p<-ggplot(data, aes(x=Accuracy, fill=Modality)) +
 geom_density(alpha=0.4)+
 facet_wrap(. ~ Species) +
 xlab("Accuracy") + ylab("Density")

library(plyr)
mu <- ddply(data, "Modality", summarise, grp.mean=mean(Accuracy))
head(mu)


# Add mean lines
a<-p+geom_vline(data=mu, aes(xintercept=grp.mean, color=Modality),
                linetype="dashed")+ xlab("Accuracy") + ylab("Density")

However, based on the output figure as
enter image description here

The mean lines are absolutely incorrect, e.g. for the first picture on the top left, there should be two lines for two density plots, but a couple of lines are created and being repeated for all the figures.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may specify both Species and Modality

plyr

dummy <- ddply(data, c("Species","Modality"), summarise, grp.mean=mean(Accuracy))

ggplot(data, aes(x=Accuracy, fill=Modality)) +
  geom_density(alpha=0.4)+
  facet_wrap(. ~ Species) +
  xlab("Accuracy") + ylab("Density") +
  geom_vline(data = dummy, aes(xintercept = grp.mean, color = Modality))

dplyr

library(dplyr)



dummy <- data %>%
  group_by(Species, Modality) %>%
  summarize(mean = mean(Accuracy))

ggplot(data, aes(x=Accuracy, fill=Modality)) +
  geom_density(alpha=0.4)+
  facet_wrap(. ~ Species) +
  xlab("Accuracy") + ylab("Density") +
  geom_vline(data = dummy, aes(xintercept = mean, color = Modality))

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading