Search code examples
rggplot2case

ggplot2 (R): Coloring scatter plot using a loop?


I have a following code, which works well:

library(ggplot2)

ggplot(data = iris, aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point(color =
               case_when(
                   iris[["Sepal.Length"]] > 7 ~ rgb(133, 188, 121, maxColorValue = 255),
                   iris[["Sepal.Length"]] > 6 ~ rgb(83, 110, 155, maxColorValue = 255),
                   iris[["Sepal.Length"]] > 5 ~ rgb(111, 112, 107, maxColorValue = 255),
                   iris[["Sepal.Length"]] > 4 ~ rgb(249, 222, 91, maxColorValue = 255),
                   TRUE ~ NA
                 )
             )

However, as you may notice, there is plenty of (unnecessary) repetition. How could I color the scatter plot using rules that are derived using a loop structure?

The following could be applied...

eval(parse(text="...string from a loop comes in here..."))

...but is there a more elegant solution available?


Solution

  • At least for the given example IMHO the easiest approach would be to use cut() to bin your value and to assign your custom colors (which as far as I get it are more or less the default ggplot2 colors) via scale_color_manual:

    library(ggplot2)
    
    iris2 <- iris |>
      transform(
        color = cut(Sepal.Length, c(4, 5, 6, 7, Inf))
      )
    
    pal_color <- scales::hue_pal()(4)[c(4, 2, 1, 3)]
    
    ggplot(data = iris2, aes(
      x = Sepal.Length, y = Petal.Length,
      color = color
    )) +
      geom_point() +
      scale_color_manual(values = pal_color)