0

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!

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Wow! Super!!! Thanks, Ronak. I will accept it as a final solution. Very cool
0

We could use ifelse

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

and then use the function

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.