Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

Here is my code at the moment:

require(ggplot2)
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)) +
  geom_point(aes())

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?

like image 794
sudo make install Avatar asked Jan 30 '14 22:01

sudo make install


3 Answers

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)) +
  geom_point(position=position_dodge(width=0.75),aes(group=group))

enter image description here

like image 167
Didzis Elferts Avatar answered Nov 03 '22 15:11

Didzis Elferts


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() +
  geom_point(position=position_jitterdodge())
  # or, if you dont need jittering
  # geom_point(position=position_jitterdodge(jitter.width = 0, jitter.height = 0)) 

jittered overlay

http://ggplot2.tidyverse.org/reference/position_jitterdodge.html

like image 36
NWaters Avatar answered Nov 03 '22 16:11

NWaters


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

library(ggbeeswarm)
library(ggplot2)

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

enter image description here

like image 2
Roman Avatar answered Nov 03 '22 16:11

Roman