Overlay geom_points() on geom_boxplot(fill=group)?

Here is my code at the moment:

value <- rnorm(40, mean = 10, sd = 1)
variable <- c(rep('A', 20), rep('B', 20))
group <- rep(c('Control', 'Disease'), 20)
data <- data.frame(value, variable, group)

ggplot(data, aes(x=variable, y=value)) +
  geom_boxplot(aes(fill=group)) +

This divides up boxplots into groups by variable the way I'd like. However, the points for all groups are overlaid, and I'd like for it to be divided up into groups. How would I go about doing this?


Use position_dodge() for the points and also add group=group inside aes() of geom_point().

ggplot(data, aes(x=variable, y=value)) +
  geom_boxplot(aes(fill=group)) +

I don't know when this was introduced, but there is a new(ish) featured called position_jitterdodge, which simplifies this, whether you want jittering or not. Usage:

ggplot(data, aes(x=variable, y=value, fill=group)) +
  geom_boxplot() +
  # or, if you dont need jittering
  # geom_point(position=position_jitterdodge(jitter.width = 0, jitter.height = 0)) 


You can try the ggbeeswarm as well. Here I compare the output of geom_beeswarm and geom_quasirandom:


ggplot(data, aes(x=variable, y=value, fill=group)) +
  geom_boxplot() +
  geom_beeswarm(dodge.width=0.75) +
  geom_quasirandom(dodge.width=.75, col=2) 

Here is an attempt to apply Didzis's suggestion to a dataset where not all groups have an outlier and thus the points don't line up with the correct box.

Data file: https://cmu.box.com/shared/static/2hxp2oms5et1ktr9hukdr539b6svq1cg.rds


d <- readRDS("2hxp2oms5et1ktr9hukdr539b6svq1cg.rds")

ggplot(d) + 
  geom_boxplot(aes(x=factor(game),y=N,fill=.group),outlier.shape=NA) + 
  geom_point(data=dd.sum1[,.SD[which(N %in% boxplot.stats(N)$out)],by=game][,.group:=factor(.group,levels=.groups)][,],aes(x=factor(game),y=N,color=.group,group=.group),
             size=.5) +
  facet_grid (type~., scales="free_x", space="free_x") +
  xlab("Game number") +
  ylab("Count") +
  scale_color_brewer("Group",palette="Set1",drop=FALSE) +
  scale_fill_brewer("Group",palette="Set1",drop=FALSE) +

Need Your Help

How to show a new view controller if the alert is validated? (objective c)

ios objective-c uiviewcontroller alert

instead of a button i'd like to change the view controller if a alert is validated but i've no idea how to do is. I use a cocoa pod for the notification (just cause the design is beautiful). every ...

ExtJs tree panel. How to scroll to a node

extjs tree scroll extjs4.1

I have a Tree Panel which I expand programmatically.