rggplot2heatmap

reversing order of heatmap category labels


I'm trying to produce a heatmap with ordered categorical variables for both x- and y-axes. The problem I'm having is that I'm unable to have the y-axis levels print in descending order. Curiously (to me), I'm able to generate the plot in the orientation that I want, but the tick labels on the y-axis don't follow suit.

library(tidyverse)

# dataframe showing frequency of precip at 4 different levels (class) for 3 months...
m <- tibble(class = 1:4,
            Jan = c(0,0,1,4),
            Feb = c(0,1,3,2),
            Mar = c(1,3,1,0)) %>% 
  mutate(class = factor(class))

# reshape data into a timeseries
ts <- 
  m %>% 
  gather(month, count, Jan:Mar) %>% 
  mutate(month = factor(month, levels = month.abb))

# generate heatmap
ggplot(ts, 
aes(
x = month, 
y = rev(class), # reversing the class here prints the map in the desired orientation
fill = count)) +
  geom_tile() +
  scale_fill_distiller(palette = "Blues", direction = 1) +
  theme_bw()

I want the higher classes (greater rainfall) at the bottom (note that Jan most frequently has precipitation in the higher classes), but the y-axis tick labels print from 4 down to 1, despite class being a factor. TIA


Solution

  • You will need to define the levels in reverse order to match your reverse order scale.

    m <- tibble(class = 1:4,
                Jan = c(0,0,1,4),
                Feb = c(0,1,3,2),
                Mar = c(1,3,1,0)) %>% 
       mutate(class = factor(class, labels=rev(1:4))) 
    

    enter image description here