Skip to content
Prev 385418 / 398506 Next

ggplot 3-color gradient scales

Hello,

If you want a predetermined number of colors, discretise the data and 
use scale_color_manual. In the code below I first compute another vector 
z, with a different range, 0 to 2. (In my first mail it was 0 to 1.)

g <- function(x, a = 0, b = 1){
   (b - a)*(x - min(x))/(max(x) - min(x)) + a
}

library(ggplot2)

df1 <- iris[3:5]
names(df1)[1:2] <- c("x", "y")
df1$z <- ave(df1$y, df1$Species, FUN = function(x) g(x, a = 0, b = 2))


Now is the step that solves the problem, to bin the vector. Other 
options could include findInterval. Then the two plot instructions are 
equivalent.

df1$z <- cut(df1$z,
              breaks = c(-Inf, 0.8, 1.2, Inf),
              labels = c("Small", "Medium", "Large"))


ggplot(df1) +
   geom_point( aes(x, y, color = z) ) +
   scale_color_manual(values = c("red", "green", "blue"))

ggplot(df1) +
   geom_point( aes(x, y, color = z) ) +
   scale_color_manual(breaks = c("Small", "Medium", "Large"),
                      values = c("Small" = "red", "Medium" = "green", 
"Large" = "blue"))


Hope this helps,

Rui Barradas


?s 10:38 de 25/08/20, April Ettington escreveu: