Home > database >  ggplot: scale_color_steps()-like color scale for ordered factors
ggplot: scale_color_steps()-like color scale for ordered factors

Time:02-12

With scale_color_steps() we can set from what to what color we want the scale to evolve by setting the low and the high argument. An example:

df <- data.frame(x= rnorm(99), y= rnorm(99), col= rnorm(99))
ggplot(df, aes(x, y, col= col))  
  geom_point()  
  scale_color_steps(low= "blue", high= "red")

cont

This works for continuous col variables but I want to achieve the same for ordered factors, i.e. I want to set that the lowest color of my lowest factor level is col1 (for example blue) and the highest col2 (for example red). Is this possible?

What I've tried: I recently asked a question about color scales and got an discr

... but the problem is that (i) the factor levels are missing in the legend (obviously) and (ii) there are more color steps in the legend then factor levels but I want them to be the same. Can we fix both with the approach above or is there another way to do it?

CodePudding user response:

This is one way to do it, though it feels a bit hacky. I'd be interested to see if there's a cleaner solution.

ggplot(df, aes(x, y, col = col))  
  geom_point(aes(fill = col), key_glyph = draw_key_rect)  
  scale_color_manual(values = colorRampPalette(c("red", "blue"))(3))  
  scale_fill_manual(values = colorRampPalette(c("red", "blue"))(3))

enter image description here


Addendum

This version is a bit less hacky (in that you don't need to forge the guides and still use scale_color_steps), but it's still somewhat involved:

ggplot(df, aes(x, y, col = as.numeric(col)))  
  geom_point()  
  scale_color_steps(low = "blue", high = "red", 
                    breaks = seq(nlevels(df$col)), 
                    limits = c(0, nlevels(df$col)   1),
                    labels = rev(levels(df$col)), name = "col")

enter image description here

  • Related