Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove grey fill for out of bounds values when using limits in scale_

Tags:

r

ggplot2

limit

I am using R (3.0.1) and ggplot2 (ggplot2_0.9.3.1) with geom_tile and scale_fill_gradient. I am using the 'limits' option in scale_fill_gradient, as shown below. The problem is that I want to get rid of the grey background that appears outside of the specified limits. I want that background to be white just like the rest of the graph due to theme_bw(). I have been unable to figure out how to do it. Thanks.

 pp <- function (n,r=4) {
 x <- seq(-r*pi, r*pi, len=n)
 df <- expand.grid(x=x, y=x)
 df$r <- sqrt(df$x^2 + df$y^2)
 df$z <- cos(df$r^2)*exp(-df$r/6)
 df
}

 p <- ggplot(pp(20), aes(x=x,y=y))
 p + theme_bw() + geom_tile(aes(fill=z)) +
     scale_fill_gradient(low="green", high="red", limits = c(-0.1, 0.1))
like image 531
Niels Janssen Avatar asked Mar 23 '23 12:03

Niels Janssen


1 Answers

Add the argument na.value="transparent" to scale_fill_gradient:

p + theme_bw() + geom_tile(aes(fill=z)) +
     scale_fill_gradient(low="green", high="red",
                         limits=c(-0.1, 0.1), na.value="transparent")

enter image description here

like image 189
David Robinson Avatar answered Apr 05 '23 21:04

David Robinson