2 min read

How to draw a waffle plot

Load packages

library(tidyverse)
#library(waffle)
library(viridis)
#library(hrbrthemes)
library(extrafont)
library(emojifont)

What’s a waffle diagram?

A waffle diagram is a variant of (stacked) bar plots or pie plots. They do not have great perceptual properties, I’d suspect, but for some purposes they may be adequate. This is best explored by example. This post draws heavily from the introduction of hrbrmstr to his Waffle package.

Let’s make up some data and a case for it

Assume you would like to explain the differences between some sampling schemes, such as random sampling, stratified sampling, ad-hoc sampling and so on. For that, some illustrative plot might come in handy. Let’s simulate a dataset appropriate to explain sampling schemes.

set.seed(42)
d <- tibble(
  id = 1:100,
  sampled = sample(c(TRUE, FALSE), size = 100, replace = TRUE)
)
d
#> # A tibble: 100 x 2
#>       id sampled
#>    <int> <lgl>  
#>  1     1 TRUE   
#>  2     2 TRUE   
#>  3     3 TRUE   
#>  4     4 TRUE   
#>  5     5 FALSE  
#>  6     6 FALSE  
#>  7     7 FALSE  
#>  8     8 FALSE  
#>  9     9 TRUE   
#> 10    10 FALSE  
#> # … with 90 more rows

Count the different values

d %>% 
  count(sampled) -> d_counted

d_counted
#> # A tibble: 2 x 2
#>   sampled     n
#>   <lgl>   <int>
#> 1 FALSE      56
#> 2 TRUE       44

Waffle 1

w0 <- ggplot(d_counted) +
  aes(fill = sampled, values = n)


w1 <- w0 +
  geom_waffle(flip = TRUE, color = "white") +
  scale_fill_manual(values = viridis(2),
                    labels = c("Yes", "No"))

w1

Waffle 2

w2 <- w1 +
  coord_equal() +
  theme_ipsum_rc(grid="") +
  theme_enhance_waffle()

w2

Pictogram Waffle

I could not get the pictogram waffle from this package to run. I assume the Font Awesome version I used has some different name, so that it is not found by the function.

However, here’s an alternative using the package emojifont.

First, choose some Font Awesome glyphs:

fa2 <- fontawesome(c("fa-user", "fa-user-circle"))

Next, come up with some data that will be arranged in “waffle format”:

d <- crossing(x = 1:10,
               y = 1:10) %>% 
  mutate(label = sample(x = fa2, size = 100, replace = TRUE))
load.fontawesome()

Last, plot using geom_tile and geom_text:

ggplot(d, aes(x = x, y = y, color = label, label = label)) +
  geom_tile(color = "white", size = .5, aes(fill = label), alpha = .2) +
  theme_void() +
  geom_text(family='FontAwesome 5 Free', size=8) +
  scale_color_manual(label = c("gewählt", "nicht-gewählt"),
                     values = c("#00998A", "grey80")) +
  scale_fill_manual( values = c("#00998A", "grey80")) +
  theme(legend.position = "none")