Home > OS >  different color scales for same aesthetic in different layers in ggplot2, without unstable packages
different color scales for same aesthetic in different layers in ggplot2, without unstable packages

Time:12-08

is it possible to have multiple color scales for different layers?

I emulated what I would like to archive by using a fill aesthetic for a geom_point with shape=21 in the example below.

library(tidyverse)

test <- tibble(
  x=c(1:4, 1:4),
  y=c(1:4, 2:5),
  a=factor(c("a", "a", "b", "b", "a", "a", "b", "b")),
  A=factor(c("A", "A", "A", "A", "B", "B", "B", "B"))
)

ggplot(test, aes(x=x, y=y))   
  geom_line(aes(colour=A), size=2)  
  geom_point(aes(fill=a), shape=21, colour=rgb(1,1,1,0), size=4)   
  scale_fill_manual(
    values = c(a="red", b="blue"),
  )   
  scale_colour_manual(
    values = c(A="green", B="yellow"),
  )

Why is this useful? An example would be: you have a quantity (y) measured over time (x) for different measurement units (first color scale) using a different method of measurement (second color scale)

In this case I can do with the workaround in the example but I think this is interesting in general.

Also of course having different scales for different layers does not make sense for all layers, scaling one layer's x axis logarithmically an the other one's linearly would not make sense in the most cases.


Edit: I can only use more or less stable packages, anything that might no longer be supported or changes its interface often does not work.

CodePudding user response:

Your requirement about "stable package" is somewhat vague, and I am surprised to hear that a CRAN package would not fulfil your requirement.

There is currently no vanilla ggplot2 way to achieve what you want and given the availability of the packages below, I don't think this is likely to come.

There are, as of today (December 2021), to my knowledge, "only" three packages available to allow creation of more than one scale for the same aesthetic. These are

I use the latter a lot and never had problems, so I think this would be a very good package for your simple use case.

  • Related