1

I'm trying to give a combined color scheme in spatial plot using ggplot2 this way:

  • A Factor (2 levels) variable is used to select the tint (in my case, orange or blue)
  • A continuous variable is used to select the saturation

I found no easier way to do that than stacking two plots, the upper one a grey gradient to simulate saturation:

    ggplot(data = italian.regions) +
  geom_sf(fill = c("#BFD6FF", "#FFEBBF")[as.numeric(as.factor(regions.lookup$`engine.top`))], lwd = .2) +
  geom_sf(aes(fill = regions.lookup$`engine.diff`), lwd = .2, alpha = .3) +
  scale_fill_gradient(high = "#666666", low = "#EFEFEF")

I use the aestethic to fill the gradient and this works. This is an example plot:

example plot

But (of course) the color legend refers to the aesthetic but it should be much more meaningful to have one describing the discrete values in 'engine.top'.

Is it possible to do so? is there an easier way to have a two-tonal, gradient color scheme without stacking two plots?

halfer
  • 19,824
  • 17
  • 99
  • 186
Gabriele B
  • 2,665
  • 1
  • 25
  • 40
  • Multiple related scales like this have been [discussed a lot](https://github.com/tidyverse/ggplot2/issues/578), with some workarounds ([here's a bunch](https://www.google.com/search?q=ggplot+multiple+color+scales+site:stackoverflow.com)). Two recent packages, multiscales and ggnewscale, try to implement something like this. Also, it's easier to help more specifically, or see how this has already been addressed, if you include a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – camille May 29 '19 at 16:15
  • tnx allot, I'll try to make a reproducible example, although it sounds really tricky due to the very wide dependencies my maps have – Gabriele B May 29 '19 at 16:38
  • You could just pull together a few simplified shapes and the indicators you're coloring them by – camille May 29 '19 at 16:41

1 Answers1

3

My prefered method is to use scale_fill_identity() and hcl(). See if this works for you

library(sf)
library(tidyverse)

# this file is already on your computer 
nc <- st_read(system.file("shape/nc.shp", package="sf"))


nc_colors <-
  nc %>% 
  mutate(
    # 220 = blue and # 40 = orange
    hue = ifelse(str_detect(CNTY_ID, "^18"), 220, 40),
    light = AREA/max(AREA)*100,
    # the hcl function returns a hex code
    hex = hcl(h = hue, l = light)
  )


ggplot() +
  geom_sf(data = nc_colors, aes(fill = hex)) +
  scale_fill_identity()

enter image description here

Another solution you can use is to do something like aes(...fill = hue, alpha = AREA) then use scale_fill_manual()

yake84
  • 3,004
  • 2
  • 19
  • 35
  • 1
    Just want to throw out that this is a beautiful solution. I so rarely see good color manipulation like this, and think to do it myself even more rarely – camille May 30 '19 at 19:43
  • This works like a charm, very elegant and efficient! Thanks a lot! – Gabriele B Jun 04 '19 at 08:21