Home > Enterprise >  How set color of points in R ggplot by function?
How set color of points in R ggplot by function?

Time:10-02

I tried to set color of points in ggplot and something not works.

Here is a simplified version of code.

library(tidyverse)

get_point_color <- function(x) {
  if(x <= 10) s <- "red"
  if((x > 10) & (x <= 20)) s <- "orange"
  if((x > 20) & (x <= 50)) s <- "blue"
  s
}

mtcars %>% 
  ggplot(aes(mpg, disp))  
  geom_point(colour = get_point_color(mpg))  
  geom_smooth()  
  theme_bw()

Any help is appreciated!

CodePudding user response:

Using case_when since it is vectorised and scale_color_identity to color the points according to the name of the color.

library(ggplot2)

get_point_color <- function(x) {
  dplyr::case_when(x <= 10 ~ "red",
                   x > 10 & x <= 20 ~ "orange",
                   x > 20 & x <= 500 ~ "blue")
}

ggplot(mtcars, aes(mpg, disp, colour = get_point_color(mpg)))  
  geom_point()  
  geom_smooth()  
  scale_color_identity()   
  theme_bw()

enter image description here

  • Related