Search code examples
rggplot2colorslegend

ggplot: How to drop certain factor level from legend while still be able to set its colour?


I need do make density plots of the age of the workers of a company. One density plot shall show age of all workers and the other split by sex. It is something like this:

# Load libraries.
library(ggplot2)
library(magrittr)

# Create data.
data.frame(Age= rnorm(100, 40, 10),
           Sex= sample(c("Male", "Female"), 100, replace= TRUE)) %>%
  dplyr::mutate(id= 1:dplyr::n()) %>%
  rbind.data.frame(., .) %>%
  dplyr::mutate(df= ifelse(duplicated(id), "All", "By sex"),
                df= factor(df, levels= c("All", "By sex")),
                Sex= ifelse(df == "All", "All", Sex),
                Sex= factor(Sex, levels= c("All", "Female", "Male"))) %>%

# Plot data.
  ggplot(data= ., mapping= aes(x= Age, col= Sex)) +
  geom_density() +
  facet_wrap(. ~ df) +
  scale_color_manual(breaks= c("Female", "Male"),
                     values= c("red", "blue", "green"))

The code above results in the following plot:

Plot

As shown in the plot I was able to drop the factor level "All" from legend. But how to specify the colour of this dropped factor level? I added different third values in scale_color_manual (here: "green") but this has no effect. How to set the colour of "All" without showing this factor level in the legend?

What I found is this where they seemingly can set the dropped levels but it does not work for me.


Solution

  • Use a named vector for values to map the colors to the categories, and specify the breaks you want to see in the legend.

      ggplot(data = ., mapping= aes(x = Age, col = Sex)) +
      geom_density() +
      facet_wrap(. ~ df) +
      scale_color_manual(values = c(All = "green", Female = "red", Male = "blue"),
                         breaks = c('Female', 'Male'))
    

    enter image description here