Building off of my previous question, with thanks to @AndrewGB for the code modifications (
CodePudding user response:
You can use the breaks
argument of scale_fill_manual
to limit the number of legend entries without limiting the actual plotted colors.
However, you need to name the colors in the values
argument explicitly:
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")
)
Created on 2022-05-10 by the reprex package (v2.0.0)