Two different color keys in ggplot

506 Views Asked by At

I would like to plot points twice using two diferent color scales:

In the exemple here 5 points are drown and color is mapped to two covariates (cov1 and cov2): cov1 and cov2 are in different scales 1 to 5 and 0.01 to 0.05 respectively.

I wish to have 2 independent color keys, one for cov1 and one for cov2, a bit like in the graph below. However on the graph below I used 'color = cov1' end 'fill = cov2' in order to bring another color key...

Any help would be appreciated.

   gg1 <- ggplot(data = df1 , aes( x = x , y = y ) ) +
   geom_point( aes(x = x , y = y - 1 , color = cov1 ))  +
   geom_point( aes(x = x , y = y + 1 , color =  cov2  )) +
   scale_y_continuous(limits = c(-3,3)) 

  gg2 <- ggplot(data = df1 , aes( x = x , y = y ) ) +
  geom_point( aes(x = x , y = y - 1 , color = cov1 ))  +
  geom_point( aes(x = x , y = y + 1 , fill =  cov2  ), pch = 21 ) +
  scale_y_continuous(limits = c(-3,3)) 

grid.arrange( gg1 , gg2 , ncol = 2 )

enter image description here

2

There are 2 best solutions below

1
Dominik Rafacz On

In basic ggplot2 it is impossible if I remember correctly. But this repository may be your answer:

https://github.com/eliocamp/ggnewscale

or this (mentioned in description of the previous one):

https://github.com/clauswilke/relayer

I haven't been using ggplot2 for quite a long time so I'm not familiar with these two, but I remember that I used one of them at least once.

I've just wrote quick example to check if it works:

d1 <- data.frame(x=1:5, y=1)
d2 <- data.frame(x=1:5, y=2)

library(ggplot2)
library(ggnewscale)

ggplot() +
  geom_point(data = d1, aes(x=x, y=y, color = x)) +
  scale_color_continuous(low = "#0000aa", high="#ffffff") +
  new_scale_color() +
  geom_point(data = d2, aes(x=x, y=y, color = x)) +
  scale_color_continuous(low = "#aa0000", high="#00aa00") 

example

And it seems to work as you want.

1
Adela On

I used your idea about combining col and fill and small hack to use different shapes for cov1 and cov2:

# sample data
my_data <- data.frame(x = 1:5,
                      cov1 = 1:5,
                      cov2 = seq(0.01, 0.05, 0.01))

library(ggplot2)

ggplot() + 
  geom_point(data = my_data, aes(x = x, y = 0.5, col = cov1), shape = 16) +
  scale_color_continuous(low = "red1", high = "red4") + 
  geom_point(data = my_data, aes(x = x, y = -0.5, fill = cov2), shape = 21, col = "white", size = 2) + 
  ylim(-1, 1)

enter image description here

Hope it helps.