library(ggplot2)
library(ggbeeswarm)
# Sample data
set.seed(007)
y <- round(rnorm(300), 1)
df <- data.frame(y = y,
group = sample(c("G1", "G2", "G3"),
size = 300,
replace = TRUE))
head(df)
## y group
## 1 2.3 G3
## 2 -1.2 G1
## 3 -0.7 G2
## 4 -0.4 G2
## 5 -1.0 G2
## 6 -0.9 G3
The ggbeeswarm package contains a function named geom_beeswarm, which can be used to create a beeswarm in ggplot2.
# Basic beeswarm plot in ggplot2
ggplot(df, aes(x = group, y = y)) +
geom_beeswarm()
By default the observations are shown all very close to each other. You can use the cex argument to increase the spacing and size to increase the size of the point.
# Beeswarm plot in ggplot2
ggplot(df, aes(x = group, y = y)) +
geom_beeswarm(cex = 3)
As with other ggplot2 charts if you want to color the observations by group you can pass the categorical variable to the color or colour argument of aes.
# Beeswarm plot in ggplot2
ggplot(df, aes(x = group, y = y, color = group)) +
geom_beeswarm(cex = 3)
If you color the observations by group a default color scale will be used. You can change the colors with scale_color_brewer, scale_color_manual or an equivalent color scale.
# Beeswarm plot in ggplot2
ggplot(df, aes(x = group, y = y, color = group)) +
geom_beeswarm(cex = 3) +
scale_color_brewer(palette = "Set2")