Basic beeswarm plot with R



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 simple beeswarm plot using the beeswarm package. We will provide reproducible code and examples.

Beeswarm Data to Viz

Packages


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

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

# install.packages("beeswarm")
library(beeswarm)


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)
print(head(iris)) # display first rows
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa

Most simple beeswarm


The package comes with a beeswarm() function that creates a beeswarm plot that can be used with only 1 argument: the numerical variable to visualize. Here, we’ll use the Sepal.Length variable from the iris dataset.

beeswarm(iris$Sepal.Length)

Flip the plot


We can easily flip the plot by setting the horizontal argument to TRUE (or vertical to FALSE):

beeswarm(iris$Sepal.Length, horizontal=TRUE)

Going further


In this post, we learned how to create a simple beeswarm plot using the beeswarm package. We used the beeswarm() function to create a basic plot.

You might be interested in how to custom the dots or how to display several groups on the beeswarm plot.

Related chart types


Violin
Density
Histogram
Boxplot
Ridgeline



Contact

This document is a work by Yan Holtz. Any feedback is highly encouraged. You can fill an issue on Github, drop me a message on Twitter, or send an email pasting yan.holtz.data with gmail.com.