简体   繁体   中英

R: Using Alpha to Control Fill

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.

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.

Not sure what you mean by "can't get alpha to work properly"; your code runs fine for me.

Small suggestions:

ggplot(d, aes(factor(x), y)) + 
  geom_rect(aes(NULL, NULL, xmin=Start, xmax=End, fill=Level), 
            alpha = 0.2, ymin=-Inf, ymax=Inf,data=Groups) + 
  geom_boxplot() +
  scale_fill_brewer(palette="Pastel1")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM