Search code examples
rggplot2colorsgeom

Is there any way to use 2 color scales on the same ggplot?


With the data separated by categories (Samples A and B), 2 layers were made, one for points and one for lines. I want to separate my data by category indicating colors for the points and also separate the lines but with different colors than those used for the points.

library(ggplot2)

Sample <- c("a", "b")
Time <- c(0,1,2)

df <- expand.grid(Time=Time, Sample = Sample)
df$Value <- c(1,2,3,2,4,6)

ggplot(data = df,
             aes(x = Time,
                 y = Value)) +
  geom_point(aes(color = Sample)) +
  geom_line(aes(color = Sample)) +
  scale_color_manual(values = c("red", "blue")) + #for poits
  scale_color_manual(values = c("orange", "purple")) #for lines

Solution

  • Making use of the ggnewscale package this could be achieved like so:

    library(ggplot2)
    library(ggnewscale)
    Sample <- c("a", "b")
    Time <- c(0,1,2)
    
    df <- expand.grid(Time=Time, Sample = Sample)
    df$Value <- c(1,2,3,2,4,6)
    
    ggplot(data = df,
           aes(x = Time,
               y = Value)) +
      geom_point(aes(color = Sample)) +
      scale_color_manual(name = "points", values = c("red", "blue")) + #for poits
      new_scale_color() +
      geom_line(aes(color = Sample)) +
      scale_color_manual(name = "lines", values = c("orange", "purple")) #for lines