Search code examples
rvariablesggplot2plotcolors

ggplot & colors: how to use the color gradient of another variable?


I'm drawing a map of my country using the shapefiles. This is the script that i'm using and it works fine

right_join(shapefiles, dataset, by = "COD_PROV") %>% 
  ggplot(aes(fill = `Real Wage 1`)) +
  geom_sf() +
  theme_void() +
  theme(legend.title=element_blank(), legend.key.size = unit(1, 'cm'),
        legend.text = element_text(size=15))+
  scale_fill_gradientn(colors = c( "#FFFFFF","#FFFF00", "#FF0000", "#000000"))

As output it fills the different regions with the gradients of the colors i've specified, which is what i was looking for.

Now, consider that I have 2 variables: 'Real Wage 1' and 'Real Wage 2'.

'Real Wage 2' has more values than 'Real Wage 1'.

What I'm trying to do is to fill the regions with 'Real Wage 1' without changing colors, but using the gradients based on the values of 'Real Wage 2'.

To be more clear, I'm trying to use the grandient of yellow, orange and red that the values of the variable 'Real Wage 2' generates and apply this scale of colors into my geographical map according with the value of the variable 'Real wage 1'.

GRADIENT

I know that the command 'geom_blank' normalizes the scale of colors, so i've tried this, but it doesn't work

right_join(shapefiles, dataset, by = "COD_PROV") %>% 
  ggplot(aes(fill = `Real Wage 1`)) +
  geom_sf() +
  theme_void() +
  theme(legend.title=element_blank(), legend.key.size = unit(1, 'cm'),
        legend.text = element_text(size=15))+
  scale_fill_gradientn(colors = c( "#FFFFFF","#FFFF00", "#FF0000", "#000000"))+
  geom_blank(dataset$`Real Wage 2`)

R replies

Error in `geom_blank()`:
! `mapping` must be created by `aes()`
Run `rlang::last_error()` to see where the error occurred.

How can I solve??


Solution

  • Use the limits argument in scale_gradient. If using another column, you can simply pass its range to the limits. I'm using a dummy example here.

    library(ggplot2)
    
    ## limiting the scale by another column in the data, here on a dummy example
    iris2 <- iris
    iris2$exp_SL <- iris2$Sepal.Length^1.1
    ## I like to define the ranges first to save typing
    lims <- range(iris2$exp_SL)
    ggplot(iris2) +
      ## using the actual values as fill/color
      geom_point(aes(Petal.Width, Sepal.Width, color = Sepal.Length)) +
      ## now use limits to limit to the range of the other column 
      scale_color_gradient(limits = lims)
    

    Created on 2023-02-22 with reprex v2.0.2