Carlos
Carlos

Reputation: 47

Add mean to grouped box plots in R using ggplot2

I have three Cultures of algae (A,B,C) at two temperatures (27C and 31C) and their densities. I want to make a box plot with Temperature in the x axis, Density in the y axis and the three cultures above each temperature (see picture below). I also need to include a dot with the mean density per culture and temperature. My script plots only one mean above each temperature but what I need is a mean for A@27C, B@27C, C@27 and A@31C, B@31C and C@31C. I tried to adapt some scripts with similar questions but I couldn’t get it to work. Any help would be much appreciated.

graph<-ggplot(Algae, aes(x = Temperature, 
                         y = Density,
                         fill=Culture))+
              geom_boxplot()+
              stat_summary(fun=mean, 
                           geom="point", 
                           shape=20, 
                           size=2, 
                           color="red", 
                           fill="red", 
                           position = position_dodge2 (width = 0.5, preserve = "single"))

enter image description here

Upvotes: 1

Views: 507

Answers (2)

Carlos
Carlos

Reputation: 47

I fixed it by adding a facet. Here is the script

graph <-ggplot(Algae, aes(x = Temperature, 
                          y = Density,
                          fill=Culture))+
               geom_boxplot()+
               stat_summary(fun=mean, 
                            geom="point", 
                            shape=21, 
                            size=2, 
                            color="black",
                            fill="violet")+
               facet_grid(.~Temperature,scales="free")
graph

Upvotes: 0

TarJae
TarJae

Reputation: 78927

Remove fill in stat_summary and adapt the width in position Here is an example with the mtcars data set:

ggplot(mtcars, aes(x = factor(am),
                   y = mpg,
                   fill=factor(cyl)))+
  geom_boxplot() +
  stat_summary(fun=mean, 
               geom="point",
               shape=20, 
               size=2, 
               color="red", 
               position = position_dodge2 (width = 0.7, preserve = "single"))

enter image description here

Upvotes: 1

Related Questions