Home > Software design >  How to remove the legend or make transparent while keeping its space in ggplot?
How to remove the legend or make transparent while keeping its space in ggplot?

Time:02-25

This question has been answered here: enter image description here

Here is the code:

ggplot(l, aes(x=year, y=annual_chg, fill=income,color=income))  
  geom_col(position = "identity", alpha = 1/2,colour= "black")    
  facet_wrap(~Class,nrow=1) 
  theme_classic() xlab(NULL) ylab(NULL) 
  theme(
    legend.text = element_text(color = "white"),
    legend.title = element_text(color = "white"),
    legend.key = element_rect(fill = "white"))   
  guides(fill = guide_legend(override.aes= list(alpha = 0)),
         colour = guide_colorbar(override.aes = list(alpha=0)))

Here is the data:

df=structure(list(year = c(2018, 2018, 2018, 2018, 2018, 2018, 2018, 
                            2018), annual_chg = c(-0.66, 0.34, 0.59, 1.54, -0.26, 0.49, 0.66, 
                                                  1.62), Class = structure(c(4L, 3L, 2L, 1L, 4L, 3L, 2L, 1L), .Label = c("Upper-middle class", 
                                                                                                                         "Middle class", "Skilled working class", "Low-skilled working class"
                                                  ), class = "factor"), income = c("gross income", "gross income", 
                                                                                   "gross income", "gross income", "net income", "net income", "net income", 
                                                                                   "net income")), row.names = c(NA, -8L), class = c("tbl_df", "tbl", 
                                                                                                                                     "data.frame"))

CodePudding user response:

You can use theme(legend.key=element_rect(colour="white")).

library(ggplot2)

ggplot(df, aes(x=year, y=annual_chg, fill=income,color=income))  
  geom_col(position = "identity", alpha = 1/2,colour= "black")    
  facet_wrap(~Class,nrow=1) 
  theme_classic() xlab(NULL) ylab(NULL) 
  theme(
    legend.text = element_text(color = "white"),
    legend.title = element_text(color = "white"),
    legend.key = element_rect(fill = "white"))   
  guides(fill = guide_legend(override.aes= list(alpha = 0, color = "white")))  
  theme(legend.key=element_rect(colour="white"))

white legend

  • Related