2013-04-27 91 views
33

在ggplot2中,我如何让图例具有半透明背景。控制ggplot2图例中的'alpha'水平

下面的代码,给出了一个完全透明的背景(和定位控制)

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")) 

但如何控制阿尔法的水平,我不相信element_rect具有这种能力。

回答

47

通过提供颜色和alpha值,您可以通过软件包scales中的函数alpha()控制半透明度。当为fill=提供颜色时,此功能可在element_rect()内使用。

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

+0

我试过了,但我的GGPLOT2报告错误 “无法找到函数阿尔法” ... ???使用最新版本,0.9.3.1 – 2013-04-27 14:28:09

+3

此函数在库(尺度)中。更新了我的答案。 – 2013-04-27 14:29:27

+0

非常好。现在工作,欢呼。 – 2013-04-27 15:03:32