如何为上下值的散点图提供颜色范围

How to give color range to scatter plot for up and down values

我想根据值 > 5 和值 < -5 以及它们之间的值为我的图赋予不同的颜色(颜色范围)。如附图一样,图中只有 2 种颜色表示大于 5 / 小于 5 以及它们之间的值。

我的代码是:

ggplot(data, aes(S1, S2, color=abs(S1-S2)>5 )) +geom_point()+ smoother

这是一个解决方案,在 ggplot 之前创建一个对应于颜色组的新变量:

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() 

编辑
如果您想用观察次数标记图例,并选择颜色:

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"))

确保您的颜色计算得到 3 个值的结果:

ggplot(data, aes(S1, S2, color=factor(ifelse(S1-S2>5,1,ifelse(S2-S1>5,2,4)) , labels = c("less","more","same")))) +geom_point()

或者在绘图之前在脚本的另一个步骤中执行此操作。