Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-functioning ggplot alphas

Tags:

r

ggplot2

I'm trying to plot a semi-transparent rectangle the same colour as the background above a density curve so it creates a lighter-toned vertical area of the latter (a hack to visualise a range of interest such as rush hours). As you can see the alpha fails. I wonder if anyone can get the following code working?

I'm aware there are other posts on ggplot's alpha channel issues (for example) but none seem to resolve this, and its not clear what the current situation is version-wise.

Thanks in advance :)

enter image description here

d <- data.frame(rnorm(100, mean = 0, sd = 100)); names(d) <- 'data'

ggplot(d) + geom_density(aes(x=data),col=NA, fill='grey30') + opts(panel.background=NULL) +
  geom_rect(aes(xmin=-30, xmax=30, ymin=0, ymax=0.005), fill='white',alpha=0.2)

ggplot(d) + geom_density(aes(x=data),col=NA, fill='grey30') + opts(panel.background=NULL) +
  geom_rect(aes(xmin=-30, xmax=30, ymin=0, ymax=0.005), fill='#FFFFFF40')
like image 522
geotheory Avatar asked Sep 09 '12 15:09

geotheory


1 Answers

It appears that you just have chosen too low alpha, try for example 1/256, which is the lowest possible amount of transparency:

ggplot(d) + geom_density(aes(x = data), col = NA, fill = 'grey30') + 
  theme(panel.background = NULL) +
  geom_rect(aes(xmin = -30, xmax = 30, ymin = 0, ymax = 0.005), 
            fill = 'white', alpha = 1/256)

enter image description here

This is an unexpected solution for me too, because taking alpha = I(1/d) means that d is a number of points that must be overplotted to give a solid colour, so we would expect different result with 1/256. As you said, that is a quite frequent issue related to geom_rect.

like image 135
Julius Vainora Avatar answered Oct 30 '22 11:10

Julius Vainora