Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling the 'alpha' level in a ggplot2 legend

Tags:

r

ggplot2

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.

like image 821
Nicholas Hamilton Avatar asked Apr 27 '13 12:04

Nicholas Hamilton


People also ask

What does Alpha mean in ggplot2?

Alpha refers to the opacity of a geom. Values of alpha range from 0 to 1, with lower values corresponding to more transparent colors.

How do I change the legend value in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))


1 Answers

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

like image 77
Didzis Elferts Avatar answered Sep 23 '22 00:09

Didzis Elferts