I am trying to make the legend key fill for a ggplot transparent. I followed the instructions on one of Hadley\'s ggplot2 guides for changing the legend key fill, but for some
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"))
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
To make use of the transparency levels, one can use:
For the entire legend:
theme(legend.background=element_rect(fill = alpha("white", 0.5)))
alpha("white", 0)
being completely transparent like element_blank()
,
and alpha("white", 1)
having no transparency.
Now, for the key - if key and background have different transparencies:
theme(legend.background=element_rect(fill = alpha("white", 0)),
legend.key=element_rect(fill = alpha("white", .5)))
Note: background transparency overrules the one for the key, i.e. background alpha must be smaller than key alpha.
This answer seems to be the simplest solution, setting legend.key = element_blank()
in the theme()
definition.