user3616494 user3616494 - 1 month ago 5x
R Question

Give color to scatter plot points based on value thershold

I have data.frame of value between -10 to 10, my data.frame has 2 columns.I wanted to create a ggplot graph.

I need to give color to points which have values more than 8 or less than -8.

How can I do this by ggplot in geom_point()?


I agree with the comments above, anyway I think this is what you are looking for

p <- runif(100, min=-10, max=10)
g <- 1:100
dat <- data.frame(p, g)
dat$colors <- 1
dat[which(dat$p < (-8) | dat$p > 8),"colors"] <- 0


ggplot(dat, aes(x=g, y=p, group=colors)) + geom_point(aes(color=as.factor(colors)))

Which results in this: enter image description here

Edit: In a previous version of this answer the different colors were expressed as a continuous variable. I changed this to a dichotomous format with as.factor.