10

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.

Dieter Menne
  • 10,076
  • 44
  • 67
Jared Eccles
  • 127
  • 1
  • 7
  • 3
    The grey area is controlled by the na.value argument to scale_fill_gradient, but even when I specify a transparent color (like na.value=rgb(1,1,1,0)) it comes out opaque, so there must be something else going on. – Fojtasek Apr 18 '12 at 16:32
  • Alright, so perhaps if we can set the limits of a scale_alpha_continuous to be dependent on the fill value (density), then set the alpha na.value=0... – Jared Eccles Apr 18 '12 at 17:28
  • no luck so far, although setting to `gray90` makes it look *almost* OK since that's the color of the background grid ... I actually suspect this is a ggplot "issue" (buglet/wishlist?) ... possibly related to https://github.com/hadley/ggplot2/issues/475 ? – Ben Bolker Apr 18 '12 at 21:59

2 Answers2

12

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

jthetzel
  • 3,603
  • 3
  • 25
  • 38
  • This also works great. Could you explain why it is not sufficient to set `alpha` in the `aes(..)` options only, but why transparency of the fill area can only be controlled by setting the range with `scale_alpha_continuous`? For example, I used `alpha = ifelse(..density.. < 1e-5, 0, 0.7)` and `scale_alpha_continuous(range = c(0, 0.7))` to make the fill area slightly transparent. – cengel Jan 30 '14 at 17:25
11

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

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453