Basic beeswarm plot with ggbeeswarm



A beeswarm plot or swarmplot is a type of data visualization that displays individual data points in a way that they don’t overlap, resulting in a swarming effect that resembles a swarm of bees.
In this post, we’ll see how to create a basic beeswarm plot in R using the ggbeeswarm package.

Beeswarm Data to Viz

Packages


For this post, we need to install and load the ggbeeswarm package.

We can install it from CRAN using install.packages("ggbeeswarm"). Then, we can load it:

# install.packages("ggbeeswarm")
library(ggbeeswarm)
library(ggplot2)


Dataset


Since beeswarm plots are made to visualize individual data points, we need a dataset that contains numerical values. Here, we’ll use the iris dataset, which is a built-in dataset in R.

We can easily load it:

data(iris)

Beeswarm with ggplot2


The package comes with 2 main functions:

In this post, we’ll focus on the geom_beeswarm() function.

ggplot(iris,aes(y=Sepal.Length,x='')) +
  geom_beeswarm()

Flip the plot


We can super easily flip the plot by changing the x and y aesthetics:

ggplot(iris,aes(x=Sepal.Length,y='')) +
  geom_beeswarm()

Custom theme


We can change the color of the points and the overall theme of the plot using the theme() function:

ggplot(iris,aes(y=Sepal.Length,x='')) +
  geom_beeswarm(color='blue') +
  theme_minimal()

Change the position behavior


By default, the geom_beeswarm() function will use the swarm method to position the points. We can change this behavior using the method argument. Here are the available options:

Here’s an example with center:

ggplot(iris,aes(y=Sepal.Length,x='')) +
  geom_beeswarm(method='center')

Going further


This post explains how to create and customize a beeswarm plot with ggbeeswarm.

You might also be interested in how to create a grouped beeswarm plot with ggplot2.

Related chart types


Violin
Density
Histogram
Boxplot
Ridgeline



❤️ 10 best R tricks ❤️

👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥