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

Time:12-07

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.

CodePudding user response:

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

  • Related