Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Thresholds for scale_alpha()

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.

like image 705
jakob-r Avatar asked Aug 14 '12 10:08

jakob-r


2 Answers

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

like image 20
Andrie Avatar answered Sep 17 '22 08:09

Andrie


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

like image 93
Brian Diggs Avatar answered Sep 20 '22 08:09

Brian Diggs