Search code examples
rggplot2scale-color-manual

How to have two scale_color_manuals in ggplot?


I am trying to plot a dataset where the points are colored using the specified colors and text labels are colored using different manually specified colors

here is a dummy code to illustrate teh issue:

  data2= mtcars |>  mutate(color=sample(3, size = nrow(mtcars), replace = TRUE))


mtcars |> 
  ggplot(aes(mpg, disp, color=factor(am)))+
  
  scale_color_manual(values=c("black","red"))+
  geom_point()+
  geom_text(data = data2, aes(mpg-1, disp, label=cyl, color=factor(color)))+
  
  scale_color_manual(values=c("green","blue", "orange", "yellow"))

the issue is that 2nd scale_color_manual override the previous one (obviously). but I cant think of the way to tell R that they are applied to different objects: one to pints other to text labels enter image description here


Solution

  • One option would be the ggnewscale package which allows for multiple scales and legends for the same aesthetic. To this end add a new_scale_color to your code:

    set.seed(123)
    
    library(dplyr)
    library(ggplot2)
    library(ggnewscale)
    
    data2 <- mtcars |> mutate(color = sample(3, size = nrow(mtcars), replace = TRUE))
    
    mtcars |>
      ggplot(aes(mpg, disp, color = factor(am))) +
      geom_point() +
      scale_color_manual(values = c("black", "red")) +
      new_scale_color() +
      geom_text(data = data2, aes(mpg - 1, disp, label = cyl, color = factor(color))) +
      scale_color_manual(values = c("green", "blue", "orange", "yellow"))