Search code examples
rggplot2geom-tile

setting colors for geom_tile with both discrete and continuous variables


I am using geom_tile function from ggplot to visualise some spatial data. I have a continous variable region_relative_rainfall and discrete variable region. I would like to create a clear plot that has contrasting colors for each level of the discrete variable. And within each level of discrete variable have that same color being sequential for the continuous variable. I only know how to change the fill and color as shown with the code below, but isn't as clear as I would like. Any tips would be much appreaciated.

# geom_tile question
library(ggplot2)
library(dplyr)
set.seed(123)
n_row = 10
n_col = 20
df = expand.grid(1:n_row, 1:n_col)
colnames(df) = c("y","x")
n = n_row * n_col
k = 5
df$region = sample(x = letters[1:k], size = n, replace = T)
df$rainfall = rlnorm(n = n, log(13), 0.4)
## normalise rainfall by region, to sum = 1 for each region
df <- df %>% 
  group_by(region) %>%
  mutate("region_relative_rainfall" =rainfall / sum(rainfall))

## Current plot, not quite what I want
ggplot(df, aes(x = x, y = y, fill = region_relative_rainfall, color = region)) +
  geom_tile() +
  theme(panel.grid = element_blank(),
        axis.text = element_blank()) +
  scale_y_reverse( lim=c(n_row,1))

Solution

  • Do you need something like this?

    library(ggplot2)
    
    ggplot(df) + aes(x = x, y = region, fill = region) +
      geom_tile(aes(alpha = region_relative_rainfall)) + 
      theme(panel.grid = element_blank(),
            axis.text = element_blank()) 
    

    enter image description here