Search code examples
rggplot2bar-chartfactorialpoints

How to plot the mean of a single factor in a barplot with


I'm having trouble to create a figure with ggplot2. In this plot, I'm using geom_bar to plot three factors. I mean, for each "time" and "dose" I'm plotting two bars (two genotypes).

To be more specific, this is what I mean: enter image description here

This is my code till now (Actually I changed some settings, but I'm presenting just what is need for):

 ggplot(data=data, aes(x=interaction(dose,time), y=b,  fill=factor(genotype)))+
 geom_bar(stat="identity", position="dodge")+
 scale_fill_grey(start=0.3, end=0.6, name="Genotype")

Question: I intend to add the mean of each time using points and that these points are just in the middle of the bars of a certain time. How can I proceed?

I tried to add these points using geom_dotplot and geom_point but I did not succeed.


Solution

  • library(dplyr)
    time_data = data %>% group_by(time) %>% summarize(mean(b))
    data <- inner_join(data,time_data,by = "time")
    

    this gives you data with the means attached. Now make the plot

     ggplot(data=data, aes(x=interaction(dose,time), y=b,fill=factor(genotype)))+
     geom_bar(stat="identity", position="dodge")+
     scale_fill_grey(start=0.3, end=0.6, name="Genotype")+
     geom_text(aes(b),vjust = 0)
    

    You might need to fiddle around with the argument hjust and vjust in the geom_text statement. Maybe the aes one too, I didn't run the program so I don't know.