Home > Back-end >  Display legend with two different colour palettes
Display legend with two different colour palettes

Time:10-25

I create the following plot in R:

library(ggplot2)
df_plot = data.frame(KL=runif(15,0,10),x=seq(0,1,length=15),y=seq(0,1,length=15))
ggplot()  
  geom_point(data = subset(df_plot, KL > 1), aes(x=x, y=y, col=KL),
             color = c(heat.colors(sum(df_plot$KL>1))), size =3)  
  geom_point(data = subset(df_plot, KL < 1), aes(x=x, y=y, col = KL), size = 3)

which is enter image description here

My problem is on the legend. It has the range with the colors of only the points that are <1 and it doesn't display the colors with the points above the >1.

is there a way to display the whole range of colors from 0up to 10 with the range [0,1] corresponding to the blue palette and the (1,10] to the heat palette?

CodePudding user response:

One option would be the ggnewscale package which allows for multiple scales and legends for the same aesthetic, i.e. doing so you could pass your heat colors to e.g. scale_color_gradientn instead of setting via the color argument and hence get a legend:

library(ggplot2)
library(ggnewscale)

set.seed(123)

df_plot <- data.frame(KL = runif(15, 0, 10), x = seq(0, 1, length = 15), y = seq(0, 1, length = 15))

pal_heat <- heat.colors(sum(df_plot$KL > 1))

ggplot()  
  geom_point(
    data = subset(df_plot, KL > 1), aes(x = x, y = y, col = KL), size = 3
  )  
  scale_color_gradientn(colors = pal_heat)  
  new_scale_color()  
  geom_point(data = subset(df_plot, KL < 1), aes(x = x, y = y, col = KL), size = 3)

  • Related