This post explains how to build a basic waffle chart with R and the waffle package. It provides several reproducible examples with explanation and R code.
waffle
packageThe waffle package is the best way to build a waffle chart in R. You can read more about this package on its github page. Something important to note is that you can’t install it directly from the CRAN. Instead, use this command line:
install.packages("waffle", repos = "https://cinc.rud.is")
There are 2 main ways to build a waffle chart using this library:
geom_waffle
geom inside a
ggplot2
call
waffle()
functionWe will focus on the second option in this blogpost.
The waffle function accepts 2 kinds of input: a vector or a data frame.
Let’s start with a first example based on a vector input. The
vector is a list of values. Each value will be represented as a
set of rectangles. The rows
argument controls how
many rows will be displayed on the chart.
By default, categories will be labeled A, B, C.. and so on. We will see later how to customize this.
# Load the library
library(waffle)
# Vector
<- c(30, 25, 20, 5)
x
# Waffle chart
waffle(x, rows = 8)
We can also build a waffle plot from a data frame.
Here a simple example with pizza topings.
The data frame requires 2 columns: the first one provides the labels, the second the quantities of each group.
# install.packages("waffle", repos = "https://cinc.rud.is")
library(waffle)
# Creating a simple data frame
<- data.frame(
mypizza ingredients = c("Cheese","Tomatoes","Mushroom","Pepperoni"),
vals = c(30, 25, 20, 5)
)
waffle(mypizza)
The waffle function allows a lot of customization to make the graphic more pleasant. In this example:
title
attribute)size
colors
)
legend_pos
)
library(waffle)
# Creating a simple data frame
<- data.frame(
mypizza ingredients = c("Cheese","Tomatoes","Mushroom","Pepperoni"),
vals = c(30, 25, 20, 5)
)
waffle(mypizza,
rows = 7, # Numbers of rows
size = 1, # width of the separator between blocks
colors = c("#E8D630", "#FF0000", "#582900","#A91101"), # Colors of each group
legend_pos = "bottom", # Position of the legend
title = "Most popular toppings on a pizza" # Title
)
That’s a very quick introduction to waffle charts with R using the
waffle
package. There is much more you can do using this
package, so feel free to visit the
waffle section of the gallery tp
browse more examples.
👋 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! 🔥