Home > Software engineering >  how to hide a legend level that has no obs with latest ggplot
how to hide a legend level that has no obs with latest ggplot

Time:05-24

Today I upgrade my ggplot2 to latest version. However I found I no longer can hide missing level when I use scale_shape_manual. Is there a way to let legend only show items with a value in the data?

As you can see, the data does not have grade C. I would like to hide the legend for C.

I used to be able to do that with na.translate = FALSE. I would like to keep legend setting with 5 levels ,and let plot auto adjust and omit the missing level.

enter image description here

enter image description here

The sample data and codes are here:

df<-structure(list(score = c(1, 9, 20, 18), grade = c("A", "B", "D", 
"E"), id = c(1, 2, 3, 4)), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame"))

ggplot(data = df)   
  geom_bar(aes(x =  id, y = score), stat = "identity",  width = 0.8)  
  geom_point(aes(x = id, y = score, shape = grade, color = grade) ) 
    scale_shape_manual(
    name = "Symbols",
    values = c("A" = 2,
               "B" = 3,
               "C" = 5,
               "D" = 6,
               "E" = 8),
    na.translate = FALSE)  
  scale_color_manual(
    name = "Symbols",
    values = c("A" = "black",
               "B" = "black",
               "C" = "blue",
               "D" = "red",
               "E" = "black"),
    na.translate = FALSE) 

CodePudding user response:

One approach could be to add breaks = df$grade to the calls to scale_..._manual

library(ggplot2)


ggplot(data = df)   
  geom_bar(aes(x =  id, y = score), stat = "identity",  width = 0.8)  
  geom_point(aes(x = id, y = score, shape = grade, color = grade) ) 
  scale_shape_manual(
    breaks = df$grade,
    name = "Symbols",
    values = c("A" = 2,
               "B" = 3,
               "C" = 5,
               "D" = 6,
               "E" = 8),
    na.translate = FALSE)  
  scale_color_manual(
    breaks = df$grade,
    name = "Symbols",
    values = c("A" = "black",
               "B" = "black",
               "C" = "blue",
               "D" = "red",
               "E" = "black"),
    na.translate = FALSE) 

Created on 2022-05-24 by the reprex package (v2.0.1)

  • Related