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?
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))
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))
http://ggplot2.tidyverse.org/reference/position_jitterdodge.html
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With