Search code examples
rggplot2fillboxplotpoints

R - plotting geom_point on top of geom_boxplot (ggplot2)


I'm having trouble plotting a geom_point() layer on top of a geom_boxplot() layer in ggplot2, and have done some research and there don't seem to be any reported issues precisely of this nature. There are 3 factors in my data set: name, genotype, and region, and my response variable is volume. I have working code to produce a plot with both layers. The problem is that the points ignore the fill factor for geom_point(), but not for geom_boxplot(). The result is that the points are all plotted in the middle of a set of boxplots for each value of name. Here is my code for constructing the plot.

meansPlot = ggplot(data=meansData,aes(x=factor(name), y=volume, fill=factor(genotype)))
meansPlot = meansPlot + 
geom_boxplot() +
geom_point() +
facet_wrap( ~ region, scales='free')

My apologies for not creating a reproducible data set -- I am not really well versed in simulating data quite yet. If there isn't an easy answer (which, I expect there is, and I'm probably just missing something), I will add simulated data to help answer the question.

Thanks!


Solution

  • I ended up mostly solving it. This code staggers geom_point() to be inline with geom_boxplot().

    meansPlot = ggplot(data=meansData, aes(x=name, y=volume, fill=genotype, color=genotype))  
    meansPlot = meansPlot +
    geom_point(position=position_jitterdodge(dodge.width=0.9)) +
    geom_boxplot(fill="white", position=position_dodge(width=0.9), alpha=0.5) +
    facet_wrap( ~ region, scales='free')
    

    Thanks everybody for your efforts.