Reputation: 127
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))
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.
Upvotes: 10
Views: 5044
Reputation: 3623
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")
Upvotes: 12
Reputation: 226067
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")
Upvotes: 11