ggplot2 make legend key fill transparent

前端 未结 5 2034
不知归路
不知归路 2021-02-07 03:27

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

相关标签:
5条回答
  • 2021-02-07 03:50

    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"))
    

    0 讨论(0)
  • 2021-02-07 04:00

    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.

    0 讨论(0)
  • 2021-02-07 04:01

    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

    0 讨论(0)
  • 2021-02-07 04:02

    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.

    0 讨论(0)
  • 2021-02-07 04:03

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

    0 讨论(0)
提交回复
热议问题