如何使用最新的 ggplot 隐藏没有 obs 的图例级别

how to hide a legend level that has no obs with latest ggplot

今天我将 ggplot2 升级到最新版本。但是我发现当我使用 scale_shape_manual 时我无法再隐藏丢失的级别。有没有办法让图例只显示数据中有值的项目?

如您所见,数据没有 C 级。我想隐藏 C 的图例。

我以前可以用 na.translate = FALSE 做到这一点。我想将图例设置保留为 5 个级别,并让 plot 自动调整并忽略缺少的级别。

示例数据和代码在这里:

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) 

一种方法是将 breaks = df$grade 添加到对 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) 

reprex package (v2.0.1)

于 2022-05-24 创建