Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 752
Jared Eccles Avatar asked Apr 18 '12 13:04

Jared Eccles


2 Answers

Another possibility, just using ifelse instead of cut.

d + stat_density2d(geom="tile", 
    aes(fill = ..density.., alpha = ifelse(..density.. < 1e-5, 0, 1)), 
    contour = FALSE) + 
scale_alpha_continuous(range = c(0, 1), guide = "none")

enter image description here

like image 64
jthetzel Avatar answered Nov 05 '22 18:11

jthetzel


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

like image 11
Ben Bolker Avatar answered Nov 05 '22 16:11

Ben Bolker