Making rank plots in R

infoart.ca
3 min readMar 18, 2024
Photo by Verne Ho on Unsplash

Rank plots are a simple but powerful way to show how the values stack up against each other, generally by plotting them in order from highest to lowest. Many users find it hard to make rank plots in R. In this tutorial, we will see an easy step-by-step method to make one in R.

Let’s first prepare some toy data out of the mtcars dataset. Our goal is to have a dataset of items and corresponding values across several time points, which will then be ranked pairwise:

df=  mtcars %>%
select(mpg,disp,wt,qsec) %>%
rownames_to_column("car") %>%
slice_head(n = 10) %>%
remove_rownames() %>% rename(car=1, 'year1'=2, 'year2'=3, 'year3'=4, 'year4'=5) %>%
COINr::rank_df() %>%
pivot_longer(cols = -car, names_to = "year", values_to = "rank") %>% arrange(car, year)


df
# A tibble: 40 × 3
car year rank
<chr> <chr> <int>
1 Datsun 710 year1 2
2 Datsun 710 year2 10
3 Datsun 710 year3 10
4 Datsun 710 year4 5
5 Duster 360 year1 10
6 Duster 360 year2 1
7 Duster 360 year3 1
8 Duster 360 year4 10
9 Hornet 4 Drive year1 4
10 Hornet 4 Drive year2 3
# ℹ 30 more rows

Next, we are going to use the ggplot2 package to visualize the ranks in the form of lines and dots:

# there are 10 unique items in the car column, 
so we need to create a custom palette with 10 colors as well

my_colors <- c("#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e",
"#e6ab02", "#a6761d", "#666666", "#e78ac3", "#984ea3")


ggplot(df, aes(x = year, y = rank, group = car, color = car)) +
geom_line(size = 2) +
geom_point(size = 6) +
geom_text(aes(label = rank), vjust = 0.6, size = 3.5, color = 'white') +
scale_color_manual(values = my_colors) +
scale_y_reverse(breaks = 1:nrow(df)) +
labs(x = "Year", y = "Rank") +
theme_minimal()

We can go an extra mile to improve the quality of the plot:

 
ggplot(df, aes(x = year, y = rank, group = car, color = car)) +
geom_line(size = .3) +
geom_point(size = 6) +
geom_text(aes(label = rank), vjust = 0.6, size = 3.5, color = 'white') +
scale_color_manual(values = my_colors) +
scale_y_reverse(breaks = 1:nrow(df)) +
labs(x = "", y = "") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
legend.title = element_blank(), legend.position = 'bottom', panel.border = element_blank()
) + scale_y_reverse(
breaks = 1:n_distinct(df$car),
labels = df %>% filter(year == 'year1') %>% arrange(rank) %>% pull(car),
sec.axis = sec_axis(
trans = I,
breaks = 1:n_distinct(df$car),
labels = df %>% filter(year == 'year4') %>%
arrange(rank) %>% pull(car))) +
scale_x_discrete(expand = c(0,.1))

--

--

infoart.ca

Center for Social Capital & Environmental Research | Posts by Bishwajit Ghose, lecturer at the University of Ottawa