Home > front end >  How can I completely remove legend.key from ggplot2 legend?
How can I completely remove legend.key from ggplot2 legend?

Time:10-03

I'm plotting a graph and I need to completely remove the legend.key from my ggplot legend. Why I need to do this? The legend starts with a number that reference the X axis breaks, and the label its too large and I don't want to keep it in the X axis. So, in the X axis i put breaks=1:15, and in legend the label starts with this numbers.

GRAPH TAHT I'M WORKING WITH

In resume, I just want to remove the legend.key from my graph. Is it possible? I have tried legend.key=element_blank(), but without sucess.

Obs.: In the code is it possible to see that I don't want the fill=legto change the colors of each bar. Everything is set to be gray and I just want to remove de legend.key.

ggplot(IC_QS, aes(x=ind,y=values)) 
  geom_boxplot(aes(fill=leg),color="black", outlier.colour = "red") 
  labs(title = "XXXXXXXXXX", 
       subtitle = "XXXXXXXXXXX",
       caption = "XXXXXXXXXXXXX") 
  scale_x_discrete(name = "", labels=1:15) 
  scale_y_continuous(name = "XXX", breaks = seq(0,10,1), expand = c(0,0.08*max(IC_QS$values))) 
  scale_fill_manual(name="Sectors", values = rep("gray", 15), labels=str_wrap(IC_QS_leg,25)) 
  theme(legend.position = "right", legend.background = element_blank(), 
        legend.key = element_blank(),legend.text = element_text(face = "bold", size = 8,),
        panel.background = element_blank(), panel.grid.major = element_line(colour = "gray", linetype = "dashed"),
        axis.title.x = element_text(face = "bold",vjust = -1), axis.title.y = element_text(face="bold", vjust =  1.5),
        axis.text = element_text(colour="black", face = "bold"), title = element_text(face = "bold"))

CodePudding user response:

Obviously we don't have your data, but here's an idea using the iris built-in data set

ggplot(iris, aes(Species, Petal.Width, fill = Species))  
  geom_boxplot()  
  scale_x_discrete(labels = seq(length(levels(iris$Species))))  
  scale_fill_manual(values = rep("grey", length(levels(iris$Species))),
                    labels = paste(seq(length(levels(iris$Species))),
                                   levels(iris$Species), sep = " - "))  
  guides(fill = guide_legend(override.aes = list(color = NA, fill = NA)))  
  theme_light(base_size = 16)  
  theme(legend.key.width = unit(0, "mm"))

enter image description here

  • Related