Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

r - Controlling the 'alpha' level in a ggplot2 legend

In ggplot2, how can I make the legend have a semi-transparent background.

The following code, gives a fully transparent background (and positioning control)

plot <- plot + theme(legend.position=c(1,1),legend.justification=c(1,1),
                       legend.direction="vertical",
                       legend.box="horizontal",
                       legend.box.just = c("top"), 
                       legend.background = element_rect(fill="transparent"))

But how can one control the level of alpha, I don't believe that element_rect has that ability.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can control semitransparency with function alpha() from package scales by providing color and alpha value. This function can be used inside element_rect() when you provide color for fill=.

library(scales)    
p<-ggplot(iris,aes(Petal.Length,Petal.Width,color=Species))+geom_point()
p+theme(legend.position=c(1,1),legend.justification=c(1,1),
        legend.direction="vertical",
        legend.box="horizontal",
        legend.box.just = c("top"), 
        legend.background = element_rect(fill=alpha('blue', 0.4)))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...