22  Beeswarm plots

Graphs in this chapter use ggrewindr::theme_tetris(), modeled on Tetris: a black well, the tetromino block colors as marks, and the pixel font Press Start 2P (bundled with the package) for the title.


Requirements:

✅ a categorical variable

✅ a numeric (continuous) variable

22.1 Description

The beeswarm plot uses points to display the distribution of a continuous variable across the levels of a categorical variable.

The points are grouped by level and spread sideways along the categorical axis (on both sides of each group by default). The shape (or swarm) of the points follows the distribution, similar to a violin plot.

We can create a beeswarm plot using the ggbeeswarm package.

22.2 Set up

PACKAGES

Install packages.

show/hide
# pak::pak("eclarke/ggbeeswarm")
library(ggbeeswarm)
library(ggplot2)
library(dplyr) # for tibble() and data manipulation

DATA

Tetris came bundled with every Game Boy, and by the 90s everyone had a high score to brag about. We’ll simulate the number of lines cleared in 80 games by each of three players. rnbinom() draws each game’s count from a negative binomial distribution, with a different average (mu) for each player: 25 lines for a casual player, 60 for a regular, and 120 for an expert. Setting the seed with set.seed() means you’ll get the same 240 games every time you run the code below.

show/hide
set.seed(1989) # same 240 games every time the code runs
tetris_games <- tibble(
  game_id = 1:240, # 240 different games of Tetris, one row each
  player = rep(c("Casual", "Regular", "Expert"), each = 80) # 80 games for each player type
  ) |>
  mutate(
    player = factor(player, levels = c("Casual", "Regular", "Expert")), # least to most skilled
    lines_cleared = rnbinom(n(),
      size = 5, # small size spreads the counts out
      mu = c(Casual = 25, Regular = 60, # average lines cleared
             Expert = 120)[as.character(player)] # (looked up for each player type)
      )
    )
glimpse(tetris_games)
#> Rows: 240
#> Columns: 3
#> $ game_id       <int> 1, 2, 3, 4, 5, 6, 7, 8, 9,…
#> $ player        <fct> Casual, Casual, Casual, Ca…
#> $ lines_cleared <dbl> 42, 6, 21, 30, 15, 36, 31,…

22.3 Distribution

A beeswarm plot draws every game as its own point, so it shows the spread of each group directly. Tetris scores are counts, but they’re much more spread out than the counts in the dot plot chapters: one bad drop can end a game early, and one good streak can keep it going for a long time. Below we’ll move from the games, to a picture, to the formula.

COUNT IT

Start with the first ten games (all from the casual player).

show/hide
head(tetris_games$lines_cleared, 10)
#>  [1] 42  6 21 30 15 36 31  9 26 30

The casual player averages about 25 lines, but these games range from 6 to 42. The summary below shows the variance for each player. For Poisson counts (like the Goosebumps books), the variance would be close to the mean. Here the variance is 5 to 29 times larger than the mean, and the gap grows with the player’s skill.

show/hide
tetris_games |> 
  group_by(player) |> 
  summarise(mean = mean(lines_cleared), variance = var(lines_cleared),
            min = min(lines_cleared), max = max(lines_cleared))

DRAW IT

The beeswarms below compare our regular player’s 80 games to 80 games drawn from a Poisson distribution with the same average (60 lines). The Poisson swarm is a tight cluster around 60. The negative binomial swarm stretches from single digits to more than twice the average, with a long tail of great games at the top.

show/hide
regular_games <- tibble(
  model = rep(c("Negative binomial", "Poisson"), each = 80),
  lines_cleared = c(
    tetris_games$lines_cleared[tetris_games$player == "Regular"],
    rpois(80, lambda = 60)))

ggplot(regular_games, aes(x = model, y = lines_cleared)) + 
  ggbeeswarm::geom_beeswarm(size = 1.6, color = "#00F0F0") + 
  geom_hline(yintercept = 60, linetype = "dashed", color = "#F5F5F5") + 
  annotate("text", x = 0.5, y = 60, label = "Average: 60 lines",
           hjust = 0, vjust = -0.5, color = "#F5F5F5") + 
  labs(title = "Same average, wider spread",
       x = NULL, y = "Lines cleared")

NAME IT

The negative binomial distribution is a common model for counts that are more spread out than a Poisson distribution allows (called overdispersion). With an average \(\mu\) and a size (or dispersion) parameter \(r\), its variance is:

\[ X \sim \text{NB}(\mu, \; r = 5), \quad \text{Var}(X) = \mu + \frac{\mu^2}{r} \]

The first term (\(\mu\)) is the Poisson variance, and the second term (\(\mu^2 / r\)) is the extra spread. For the regular player that’s \(60 + 3600 / 5 = 780\), compared to just 60 for a Poisson distribution. Because the extra spread grows with \(\mu^2\), the expert’s games (\(\mu = 120\)) spread out much more than the casual player’s (\(\mu = 25\)). As \(r\) gets larger, the extra term shrinks and the negative binomial turns into a Poisson. Try size = 500 in rnbinom() and the three swarms tighten up.

22.4 Grammar

CODE

  • Create labels with labs()

  • Initialize the graph with ggplot() and provide data

  • Map player to the x axis

  • Map lines_cleared to the y axis

  • Add the ggbeeswarm::geom_beeswarm() layer (with alpha) and set the point color

show/hide
labs_beeswarm <- labs(
    title = "Tetris",
    caption = "Simulated data",
    subtitle = "Lines cleared in 80 games by each player",
    x = "Player",
    y = "Lines cleared")
ggp2_beeswarm <- ggplot(data = tetris_games,
    aes(x = player,
        y = lines_cleared)) +
    ggbeeswarm::geom_beeswarm(alpha = 2 / 3, color = "#00F0F0")
ggp2_beeswarm +
    labs_beeswarm

GRAPH

Adjust the shape of the swarm using method (below), or place the points with the geom_quasirandom() function (not shown here).

22.5 More info

Below are some additional arguments and methods for beeswarm plots.

22.5.1 method


Use method to adjust the shape of the beeswarm (swarm, compactswarm, hex, square, center, or centre)

Set the point shape to 21 to control the fill and color

show/hide
ggp2_compact_swarm <- ggplot(data = tetris_games,
    mapping = aes(x = player,
                  y = lines_cleared)) +
    ggbeeswarm::geom_beeswarm(
      aes(fill = player),
        method = 'compactswarm',
        shape = 21,
        color = "#ffffff",
        alpha = 2/3, size = 1.7,
        show.legend = FALSE)
ggp2_compact_swarm +
    # add labels
    labs_beeswarm

22.5.2 side


To place the points on only one side of each group, use the side argument (1 for the right side, -1 for the left, and 0, the default, for both).

show/hide
ggp2_rside_swarm <- ggplot(data = tetris_games,
    mapping = aes(x = player,
                  y = lines_cleared)) +
    ggbeeswarm::geom_beeswarm(
      aes(fill = player),
        side = 1, # right side only
        shape = 21,
        color = "#ffffff",
        alpha = 2/3,
        size = 1.7,
        show.legend = FALSE)
ggp2_rside_swarm +
    # add labels
    labs_beeswarm

22.5.3 cex


The cex argument controls the “scaling for adjusting point spacing”

show/hide
ggp2_beeswarm_cex <- ggplot(data = tetris_games,
    mapping = aes(x = player,
                  y = lines_cleared)) +
    ggbeeswarm::geom_beeswarm(
      aes(fill = player),
        cex = 1.6,
        shape = 21,
        color = "#ffffff",
        alpha = 2/3,
        size = 1.7,
        show.legend = FALSE)
ggp2_beeswarm_cex +
    # add labels
    labs_beeswarm

22.5.4 geom_jitter()


geom_jitter() isn’t a true beeswarm: it adds random noise to each point’s position, so points can still land on top of each other. Below we set width to spread the points sideways and height to 0 so no count moves up or down (the caption notes the jitter).

show/hide
ggp2_jitter_swarm <- ggplot(data = tetris_games,
    mapping = aes(x = player,
        y = lines_cleared)) +
    geom_jitter(
        aes(fill = player),
        height = 0,
        width = 0.11,
        shape = 21,
        color = "#ffffff",
        alpha = 2 / 3,
        size = 1.7,
        show.legend = FALSE)
ggp2_jitter_swarm +
    # add labels
    labs_beeswarm +
    labs(caption = "Simulated data; points jittered to the side at random")