7

I used this Question (ggplot scale color gradient to range outside of data range) to create a gradient within a specific range but now I have the problem, that all colors outside these limits are grey. I mean, it is logic to me but I wanted to have those to have the same color as the closest point.

ggplot(data.frame(a=1:10), aes(1, a, color=a)) + 
  geom_point(size=6) + 
  scale_colour_gradientn(colours=c('red','yellow','green'), limits=c(2,8))

So the top points should be green and the lower point should be red as well. So what I am looking for is a range like limits=c(<2,>8) but I know this is not working

halfer
  • 19,824
  • 17
  • 99
  • 186
drmariod
  • 11,106
  • 16
  • 64
  • 110
  • Workaround can be: `color = ifelse(a < 2, 2, ifelse(a > 8, 8, a))` – pogibas Feb 28 '18 at 11:24
  • Is this what you want? https://stackoverflow.com/a/23655697/1527403 – Stephen Henderson Feb 28 '18 at 11:28
  • 1
    Ahh - I see someone has answered..incidentally I think this should be documented better in the scale_colour_gradient page - where oob is mentioned but not explained or demonstrated. – Stephen Henderson Feb 28 '18 at 11:30
  • This option never jumped into my eyes... Will have a look into some documentation, I might need this more often! – drmariod Feb 28 '18 at 11:31
  • @StephenHenderson Agreed; if you type `scales::squish` you see that the function basically does the same as what @PoGibas suggested. It can also be used as a template for writing your own functions. – Maurits Evers Feb 28 '18 at 11:36

1 Answers1

18

You can specify how to deal with out-of-bounds values via argument oob; for example, scales::squish "squishes" values into the range specified by limits:

ggplot(data.frame(a=1:10), aes(1, a, color = a)) +
    geom_point(size = 6) +
    scale_colour_gradientn(
        colours=c('red','yellow','green'), 
        limits=c(2,8), 
        oob = scales::squish);

enter image description here

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68