Faceting and Reordering with ggplot2

Faceting and reordering: reorder_within() tidytext
Faceting and reordering: reorder_within() tidytext

Faceting is a great data visualization technique that uses “small multiples” i.e. the use of same type of plots multiple times in a panel. Each “small multiple” is a same type of plot but for a different group or category in the data.

ggplot2 makes it really easy to make such “small multiples” with faceting. One of the functions in ggplot2 to make facetted plots is facet_wrap(). One of the ways I like to think about facetting is that it brings the group_by() idea to plotting. Basically, it splits your original data into multiple smaller data frames and makes the same plot on each of the smaller data frame. For example, if we have life expectancy data over multiple years for different continents and we can use “facet_wrap()” to make small multiples of liveExp vs continent for each year.

Recently, came across a nagging problem with faceting or reordering while making faceted barplots. Obviously, this was not first time someone had seen the problem. In fact, the amazing Julia Silge has a solution built in as part of tidytext package.

The problem is kind of hard to explain without actually showing the plots. So let us go ahead and use ggplot2’s facet_wrap() to bargraph in small multiples and try re-order within each “small multiple”.

We will be using gapminder data for this. Let us first load tidyverse and gapminder library.

libarray(tidyverse)
library(gapminder)

Let us filter gapminder data to make it easy for our facet_wrap() example. Mainly, we subset the data to have fewer data points and filter the data to contain data for four years. Then we sort by lifeExp for each country and year by using group_by() and arrange.

set.seed(42)
countries_sorted <- gapminder %>% 
  sample_n(800) %>%
  filter(year %in% c(1952, 1972, 1992, 2002)) %>%
  group_by(country,year) %>%
  arrange(-lifeExp) %>%
  select(country,year,lifeExp)

Now we have the data that we wanted i.e. life expectance values for countries in certain years sorted in descending order.

countries_sorted %>% head()

## # A tibble: 6 x 3
##   country      year     lifeExp
##   <fct>       <int> <dbl>
## 1 Japan        2002  82  
## 2 Iceland      2002  80.5
## 3 Australia    2002  80.4
## 4 Israel       2002  79.7
## 5 New Zealand  2002  79.1
## 6 Iceland      1992  78.8

Let us use this data to make a bar plot of bottom 10 countries with lowest life expectancy values for each year. To do that we first need to group_by() year and get the bottom 10 countries with lowest life expectancy. We can get bottom 10 countries using top_n() function but with negative number. Here want to generate a plot for each year i.e. we want to facet by “year” In our data frame year is integer variable. Let us convert to factor with mutate() function.

And now we are ready to make our first faceting. We will start with making barplot with geom_col() function, where x-axis is country and y-axis is the lifeExp value. We use fill to color the bars and use show.legend=FALSE to remove legends for the barplot. Finally, we add our faceting variable year with facet_wrap() function with scales=”free_y” to specify that each bar plot can have different countries .

countries_sorted %>%
  group_by(year) %>%
  top_n(-10) %>%
  ungroup() %>%
  mutate(year=as.factor(year)) %>%
  ggplot(aes(x=country,y=lifeExp, fill=year)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~year, scales="free_y")+
  coord_flip()

With the above code chunck for making facetted barplot, we get a really nice looking plot as shown below. We have four panels for each year in a 2 x 2 matrix and a barplot in each panel with bottom 10 countries with lowest life expectancies.

Barplot Faceting in ggplot2: facet_wrap()

I ran into problems, when I wanted to make one minor improvement, or I thought it was minor. That minor improvement that I wanted was to sort or reorder each barplot by life expectancy. This is something pretty easy to do and one would have a lot of times with out faceting.

We can use fct_reorder() in forcats package or reorder() function in base R to reorder the countries by lifeExp value. So we use mutate to update the country variable after sorting and go ahead to make barplots with facet_wrap() for each year.

countries_sorted %>%
  group_by(year) %>%
  top_n(-10) %>%
  ungroup() %>%
  mutate(year=as.factor(year),
         country=fct_reorder(country,lifeExp)) %>%
  ggplot(aes(x=country,y=lifeExp, fill=year)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~year, scales="free_y")+
  coord_flip()

At a first quick look our effort to sort bars of barplot within each year seemed to have worked. However, at a careful look at the plot shows that our barplot with in each is not completely sorted.

Faceting and Reordering: First Try

tidytext, the R package for doing text analysis in tidy way (And a part of the book https://www.tidytextmining.com/) offers a solution with the function reorder_within(). Giving a bit of history on the solution, Julia describes

Back in 2016, Tyler Rinker put together a solution for this problem, and David Robinson has had this wrapped up in some functions in his personal R package for a while now. Thanks to a PR from Tim Mastny, this functionality is now available in tidytext, as of version 0.2.1.

Let us load tidytext library.

library(tidytext)

reorder_within() is the function in tidytext package we will be using to reorder within each faceting group. We will use reorder_within() function inside mutate() function with three arguments. Not sure why, the name “reorder_within()” has some kind of zen to it 🙂 The function also will bring zen to the plot 🙂

The first argument is “country”, the variable we want to reorder, the second argument is lifeExp, the variable we want to reorder by and third argument is “year”, the variable corresponding to the group we want to reorder within. In addition to reorder_within() function, we also use scale_x_reordered() to make the reorder complete. Without scale_x_reordered() our y-axis labels (country) will have group information (year) as well.

countries_sorted %>%
  group_by(year) %>%
  top_n(-10) %>%
  ungroup() %>%
  mutate(year=as.factor(year),
         country=reorder_within(country,-lifeExp, year)) %>%
  ggplot(aes(x=country,y=lifeExp, fill=year)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~year, scales="free_y")+
  coord_flip()+
  scale_x_reordered() +
  scale_y_continuous(expand = c(0,0)) 

Now we get faceted barplot, nicely ordered within each group as intended. Woo hoo. thanks reorder_within().

Faceting and reordering: reorder_within() tidytext