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 :)
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')
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)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With