Ggplot2: Thresholds for scale_alpha ()

Can I set thresholds for color scales?

Take a 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

I want values ​​below 0.5 to get an alpha value of 0, so the bottom left half will be invisible. Obviously, I could convert the source data, but that would destroy the legend.

+4
source share
2 answers

The threshold works, and values ​​outside this threshold are set to NA ; the problem is that alpha of NA gets rendered as full opacity. By setting na.value on a scale to 0 , you will get the desired results.

 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

+11
source

None of my attempts to use the scales to control alpha have been 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 do not want to display 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

+4
source

All Articles