Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove fill around legend key in ggplot

Tags:

r

ggplot2

I would like to remove the gray rectangle around the legend. I have tried various methods but none have worked.

ggtheme <- 
theme(
axis.text.x = element_text(colour='black'),
axis.text.y = element_text(colour='black'),
panel.background = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_rect(colour='black', fill=NA),
strip.background = element_blank(),
legend.justification = c(0, 1),
legend.position = c(0, 1),
legend.background = element_rect(colour = NA),
legend.key = element_rect(colour = "white", fill = NA),
legend.title = element_blank()
)

colors <- c("red", "blue")
df <- data.frame(year = c(1:10), value = c(10:19), gender = rep(c("male","female"),each=5))
ggplot(df, aes(x = year, y = value)) + geom_point(aes(colour=gender))  +
stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1, 
    aes(group = gender, colour=gender)) +
ggtheme + scale_color_manual(values = colors) 

enter image description here

like image 613
Arthur Rose Avatar asked Jan 11 '14 18:01

Arthur Rose


3 Answers

theme_set(theme_gray() + theme(legend.key=element_blank())) 

If you want also to remove grey background:

theme_set(theme_bw() + theme(legend.key=element_blank())) 
like image 124
jl-blancopastor Avatar answered Oct 18 '22 17:10

jl-blancopastor


You get this grey color inside legend keys because you use stat_smooth() that as default makes also confidence interval around the line with some fill (grey if fill= isn't used inside the aes()).

One solution is to set se=FALSE for stat_smooth() if you don't need the confidence intervals.

  +stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1, 
              aes(group = gender, colour=gender),se=FALSE) 

Another solution is to use the function guides() and override.aes= to remove fill from the legend but keep confidence intervals around lines.

  + guides(color=guide_legend(override.aes=list(fill=NA)))
like image 43
Didzis Elferts Avatar answered Oct 18 '22 18:10

Didzis Elferts


+ theme(legend.background=element_blank())
like image 24
Ivone de Bem Oliveira Avatar answered Oct 18 '22 18:10

Ivone de Bem Oliveira