Home > Net >  Sorting a dataframe to create a "quilt" chart using geom_tile in ggplot2
Sorting a dataframe to create a "quilt" chart using geom_tile in ggplot2

Time:05-26

I am looking to create a "quilt" chart that would show the best performing category in each year. This is a fairly common chart, but I have no idea how to produce this in R. Below is a simple reproducible example.

fruit <- c("Apples", "Oranges", "Pears", "Peaches")
yield2020 <- c("200", "100", "250", "125")
yield2021 <- c("40", "90", "85", "100")
yield2022 <- c("150", "110", "150", "170")
DF <- data.frame (Fruit, yield2020, yield2021, yield2022)

As you can see in DF, each year, Apples, Oranges, Peaches, and Pears have different output levels. I'm looking to create a geom_tile chart that would show Pears as the top performer in 2020, Peaches in 2021, and Peaches again in 2022, with the other fruit groups shown, color coded, below it. Any advice is greatly appreciated!

I found the below example of a different quilt chart, which might help frame my ultimate goal here

CodePudding user response:

One option to achieve your desired result would be to reshape your data to long and to add a column with the rank per year which could then be mapped on the y aes. Additionally I use scale_y_reverse to put the top performers on top of the chart:

library(dplyr)
library(tidyr)
library(ggplot2)

df <- DF |> 
  pivot_longer(-fruit, names_to = "year", names_prefix = "yield") |> 
  mutate(across(c(year, value), as.numeric)) |> 
  group_by(year) |> 
  mutate(rank = rank(-value, ties.method = "first"))

ggplot(df, aes(year, rank, fill = fruit))  
  geom_tile()  
  geom_text(aes(label = paste(fruit, value, sep = "\n")))  
  scale_y_reverse()  
  guides(fill = "none")

  • Related