是否有仅显示图例键子集的 R 函数?

Is there an R function for displaying only a subset of legend keys?

基于我之前的问题,感谢@AndrewGB 对代码的修改 (),我有一个包含 24 个柱的数据集(状态为 high/low 的各个类别)。

在我的类别中,我有一个类别类型,这意味着我只需要显示图例键的一个子集(即,仅显示唯一颜色)。在我提供的玩具数据中,它类似于“Plant Type A”(粉红色)和“Plant Type B”(蓝色)以及“Control”(灰色)。

我的预期输出是仅绘制独特的图例颜色,然后为这些键提供可自定义的标签。

library(ggplot2)
library(data.table)

dat <- as.data.table(cbind(iris, Status = rep(c("High", "Low"), 75)))
dat <- rbind(dat, data.frame(Petal.Width = sample(iris$Petal.Width, 30, replace = T),
      Species = "Control", 
      Status = "Control"), fill = T)

ggplot(dat, aes(x = Species,y = Petal.Width, fill = Status)) +
  geom_boxplot(position = position_dodge(width = 0.9)) +
  scale_fill_manual(values = c("red", "pink",
                               "red", "pink",
                               "blue", "slateblue", "grey"))

ggplot(dat, aes(x = Species, y = Petal.Width, fill = interaction(Status,Species))) +
  geom_boxplot(position = position_dodge(width = 0.9)) +
  scale_fill_manual(values = c("red", "pink",
                               "red", "pink",
                               "blue", "slateblue", "grey"))

传说将是:

Plant Type A: High Status (red)
Plant Type A: Low Status (pink)
Plant Type B: High Status (blue)
Plant Type B: Low Status (slateblue)
Control - no status (grey)

我研究了 override.aesguidesscale_fill_manual - breaks,但如果不弄乱绘制的颜色,似乎无法使它正常工作。

您可以使用 scale_fill_manualbreaks 参数来限制图例条目的数量,而不限制实际绘制的颜色。 但是,您需要在 values 参数中明确命名颜色:

library(tidyverse)
library(data.table)
#> 
#> Attaching package: 'data.table'
#> The following objects are masked from 'package:dplyr':
#> 
#>     between, first, last
#> The following object is masked from 'package:purrr':
#> 
#>     transpose

dat <- as.data.table(cbind(iris, Status = rep(c("High", "Low"), 75)))
dat <- rbind(dat, data.frame(
  Petal.Width = sample(iris$Petal.Width, 30, replace = T),
  Species = "Control",
  Status = "Control"
), fill = T)

dat %>%
  mutate(fill = Species %>% paste0(Status)) %>%
  ggplot(aes(x = Species, y = Petal.Width, fill = fill)) +
  geom_boxplot() +
  scale_fill_manual(
    values = c(
      setosaHigh = "red", setosaLow = "pink",
      versicolorHigh = "lightgreen", versicolorLow = "darkgreen",
      virginicaHigh = "darkblue", virginicaLow = "lightblue",
      ControlControl = "purple"
    ),
    breaks = c("virginicaLow", "virginicaHigh", "ControlControl")
  )

reprex package (v2.0.0)

于 2022-05-10 创建