I want to give different color (color range) to my plot based on values > 5 and value < -5 and values between them. Like the attached image, in image there is just 2 color for more than 5 / less than 5 and values between them.
my code is:
ggplot(data, aes(S1, S2, color=abs(S1-S2)>5 )) +geom_point()+ smoother
Here is a solution creating a new variable corresponding to color groups before the
set.seed(1) df = data.frame(x = rnorm(1000,1,10)) df$y = df$x + rnorm(1000,1,5) df$col = NA df$col[(df$x - df$y) > 5] = "g1" df$col[(df$x - df$y) < 5 & (df$x - df$y) > -5] = "g2" df$col[(df$x - df$y) < -5] = "g3" ggplot(df, aes(x, y, color = col)) + geom_point()
If you want to label legend with number of observations, and choose the colors:
library(plyr) df_labels = ddply(df, "col", summarise, n = n()) ggplot(df, aes(x, y, color = col)) + geom_point() + scale_color_manual(labels = df_labels$n, values = c("g1" = "red", "g2" = "blue", "g3" = "green"))