rggplot2viridisscale-color-manual

use two different viridis colour palettes in a single plot


I would like to use two different viridis colour palettes with scale_color_viridis_c to show differences between the two different groups (a and b). Is there a way to change my code below in a way that would allow this?

example plot (working):

data.frame(site  = sample(LETTERS[1:4], 10000, replace = TRUE),
           group = sample(letters[1:2], 10000, replace = TRUE),
           x     = rnorm(10000, 20, 5)) %>% 
  mutate(y = x + rnorm(10000, 0, 1),
         z = rnorm(10000, 0, 1)) %>% 
  ggplot(aes(x, y, col = z)) + geom_point() + facet_wrap(~site) +
  scale_color_viridis_c(option = "plasma")

something like:

scale_color_viridis_c(option = c("a" = "plasma", "b" = "viridis")

Solution

  • I suggest the ggnewscale package. You will need to filter/split the dataset for each group "a" and "b", with a geom_point() call for each, and a new_scale_color() in between.

    library(tidyverse)
    library(ggnewscale)
    
    data.frame(site  = sample(LETTERS[1:4], 10000, replace = TRUE),
               group = sample(letters[1:2], 10000, replace = TRUE),
               x     = rnorm(10000, 20, 5)) %>% 
      mutate(y = x + rnorm(10000, 0, 1),
             z = rnorm(10000, 0, 1)) %>% 
      ggplot(aes(x, y)) + geom_point(data = . %>%  filter(group =="a"), aes(col = z)) + facet_wrap(~site) +
      scale_color_viridis_c(option = "plasma") +
      labs(col= "z group a")+
      new_scale_color() +
      geom_point(data = . %>%  filter(group =="b"), aes(col = z)) + 
      scale_color_viridis_c(option = "viridis")+
        labs(col= "z group b")
    

    Created on 2024-05-28 with reprex v2.1.0