palmerpenguins::penguins |>
group_by(species) |>
count() |>
mutate(
species = factor(species, levels = c("Adelie", "Gentoo", "Chinstrap"))
) |>
ggplot() +
waffle::geom_waffle(
aes(fill = species, values = n),
colour = "#FFFFFF",
make_proportional = FALSE,
size = 2
) +
labs(fill = "Species") +
coord_equal() +
theme_void() +
theme(legend.position = "top")Two rstats dataviz aha moments from this morning
data-visualisation
ggplot2
r-how-to
#1: 🧇 ordering the fill colour when using waffle::geom_waffle(), and #2: 🐮 getting rid of white space around a plot with fixed coords (such as, for example, a waffle plot)
While making a waffle chart, neither the order of the colours, nor the way the graph rendered were working for me… So here’s what I ended up doing.
Fixing the order mismatch
The order of the fill colour in the waffles is determined by the order in the dataframe, not by the order of factor levels. To make sure the waffle is in the order you want, rearrange your dataframe first!
Here we have them in the wrong order…
And here we’ve fixed it
palmerpenguins::penguins |>
group_by(species) |>
count() |>
mutate(
species = factor(species, levels = c("Adelie", "Gentoo", "Chinstrap"))
) |>
arrange(desc(n)) |>
ggplot() +
waffle::geom_waffle(
aes(fill = species, values = n),
colour = "#FFFFFF",
make_proportional = FALSE,
size = 2
) +
labs(fill = "Species") +
coord_equal() +
theme_void() +
theme(legend.position = "top")Sorting out the background
Integrating a plot into a report styled with a coloured background can be a pain when using a plot which has fixed coords or uses coord_polar() because you end up with white space around it and a lot of trial an error with plot sizes to get rid of it!
- 🐮 {cowplot} to the rescue!
# Output 1 - retains white space around the plot
plot +
waffle::geom_waffle(
aes(fill = species, values = n),
colour = "lightblue",
make_proportional = FALSE,
size = 2
) +
theme(plot.background = element_rect(fill = "lightblue", color = "lightblue"))# Output 2 - white space is gone!
waffle_plot <- plot +
waffle::geom_waffle(
aes(fill = species, values = n),
colour = "lightblue",
make_proportional = FALSE,
size = 2
)
cowplot::plot_grid(waffle_plot) +
theme(plot.background = element_rect(fill = "lightblue", color = "lightblue"))Now to get some lunch - waffles, anyone?
(Code snippet for those two outputs: gist.github.com/cararthompson/8e9451341cde62c5e89f878c3b8…)
Reuse
Citation
For attribution, please cite this work as:
Thompson, Cara. 2022. “Two Rstats Dataviz Aha Moments from This
Morning.” December 8, 2022. https://www.cararthompson.com/posts/2022-12-08-two-rstats-dataviz-aha-moments/.



