6

Is it possible to specify thresholds for color-scales?

Look at this example:

xy <- expand.grid(x=1:20,y=1:20)
xyd <- data.frame(xy,z=runif(400),a=rowSums(xy)/40)
g <- ggplot(xyd, aes(x=x, y=y, fill=z, alpha=a)) + 
       geom_tile() + 
       scale_alpha(range=c(0,1), limits=c(0.5,1))
g

Scale_alpha only applies to values within the given limits

What I want is that Values of a below 0.5 get an alpha value of 0 so that the lower left half will be invisible. Obviously I could transform the original data but that would destroy the legend.

Community
  • 1
  • 1
jakob-r
  • 6,824
  • 3
  • 29
  • 47

2 Answers2

15

The threshold is working and the values outside that threshold are set to NA; the problem is that an alpha of NA is getting rendered as full opacity. Setting the na.value on the scale to 0 gets the results you want.

ggplot(xyd, aes(x=x, y=y, fill=z, alpha=a)) + 
       geom_tile() + 
       scale_alpha(range=c(0,1), limits=c(0.5,1), na.value = 0)

enter image description here

Brian Diggs
  • 57,757
  • 13
  • 166
  • 188
4

None of my attempts to use the scales to control alpha were completely successful. My best attempt was to use ifelse to control the value of a:

ggplot(xyd, aes(x=x, y=y, fill=z)) + 
  geom_tile(aes(alpha=ifelse(a<=0.5, 0, a))) +
  scale_alpha(range=c(0,1))

enter image description here


So, a different approach is required: remove the values that you don't want to plot from the data:

xyd <- with(xyd, xyd[a>0.5, ])

ggplot(xyd, aes(x=x, y=y, fill=z)) + 
  geom_tile(aes(alpha=a))

enter image description here

Andrie
  • 176,377
  • 47
  • 447
  • 496
  • But look, the alpha values for the diagonal pixels are a lot less transparent then in my example. What would work is: `ggplot(xyd, aes(x=x, y=y, fill=z)) + geom_tile(aes(alpha=ifelse(a<=0.5, 0.5, a))) + scale_alpha(range=c(0,1), limits=c(0.5,1))` But how do I then let the legend know, that there are also values below 0.5 ? – jakob-r Aug 14 '12 at 11:29