ggplot2 make legend key fill transparent

I was going crazy with this behavior as well, so here is a working solution for your example:

plot + guides(color=guide_legend(override.aes=list(fill=NA)))

Check this thread for more information.


Additionally to legend.key = element_blank() you can put legend.background=element_blank() within theme(), to make the text transparent as well

This will also make the default white background transparent when using gg_themes


This answer seems to be the simplest solution, setting legend.key = element_blank() in the theme() definition.


You could trick it if you want. Add a second geom_smooth(). The first with a confidence band and you don't show the legend. With the second one you remove the band but show the legend.

df$Color <- "Red"
df1 <- df
(plot = ggplot() +
  geom_smooth(data=df, aes(data1, data2,colour=Color), se = TRUE, show.legend = FALSE) + 
  geom_smooth(data=df1, aes(data1, data2,colour=Color), se=FALSE) +
  geom_abline(intercept=0, slope=1,linetype="dashed", color = "black")+
  scale_x_continuous(expand=c(0,0), limits=c(0,100)) + 
  scale_y_continuous(expand=c(0,0), limits=c(0,100))+
  theme_classic()+
  labs(y="data2", x="data1", 
       title="sample 1 data1 vs data2") +
  theme(plot.title = element_text(size=18, face="bold"),
        legend.key = element_rect(colour = "transparent", fill = "white"),
        legend.justification = c(1,0), legend.position = c(1,0))+
  scale_color_discrete(name="Sample"))

enter image description here

Tags:

Plot

R

Ggplot2