Search code examples
rplotggplot2alphafill

ggplot2: Set alpha=0 for certain points depending on fill value


I'm currently working on a project that involves creating plots very similar to examples in Hadley's ggplot2 0.9.0 page regarding stat_density2d().

library(ggplot2)
dsmall <- diamonds[sample(nrow(diamonds), 1000), ]
d <- ggplot(dsmall, aes(carat, price)) + xlim(1,3)
d + stat_density2d(geom="tile", aes(fill = ..density..), contour = FALSE)
last_plot() + scale_fill_gradient(limits=c(1e-5,8e-4))

enter image description here

Now, what I am struggling with is a way to essentially turn alpha off (alpha=0) for all tiles not in the fill-range. So every grey tile seen in the image, the alpha should be set to 0. This would make the image a lot nicer, especially when overlaying on top of a map for example.

If anyone has any suggestions, this would be greatly appreciated.


Solution

  • This seems to work:

    d + stat_density2d(geom="tile", 
         aes(fill = ..density.., 
         alpha=cut(..density..,breaks=c(0,1e-5,Inf))), 
         contour = FALSE)+
     scale_alpha_manual(values=c(0,1),guide="none")
    

    enter image description here