2013-04-27 94 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