Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Using Alpha to Control Fill

Tags:

r

ggplot2

alpha

I'm trying to use alpha to control the transparency of the fill of my graphic. I understand that the alpha function has been moved to the scales package, but I still can't get it to work.

Data Set:

library(scales)
library(ggplot2)
Groups <- data.frame(Level=c("High", "Above Average", "Average", "Below Average", "Low"),       
                     Start=c(7.5, 5.5, 4.5, 2.5, .5), End=c(11.5, 7.5, 5.5, 4.5, 2.5)) 
Groups$Start<-as.numeric(as.character(Groups$Start))

d <- data.frame(x=1:10, y=1:10)

basicBox <- ggplot(d, aes(factor(x), y)) + geom_boxplot()
basicBox + 
  geom_rect(aes(NULL, NULL, xmin=Start, xmax=End, fill=Level), ymin=0, ymax=20, data=Groups) + 
  scale_fill_manual(values=alpha(c("red", "blue", "green", "grey", "purple"), 0.2))

Similar code can be found on page 86 of Hadley Wickham's ggplot2. When I don't load the scales library, I get and error saying that R doesn't recognize the alpha function, but even after I load scales I can't get alpha to work properly.

like image 427
Burton Guster Avatar asked Dec 15 '22 22:12

Burton Guster


1 Answers

If I get what you're asking, it should be something like this:

basicBox + 
  geom_rect(aes(NULL, NULL, xmin=Start, xmax=End, fill=Level), 
            ymin=0, ymax=20, data=Groups, alpha=0.2) + 
  scale_fill_manual(values=c("red", "blue", "green", "grey", "purple"))

I put the alpha argument in geom_rect and didn't use it as a function.

like image 139
Jared Avatar answered Dec 31 '22 07:12

Jared