3

我有数据被打包成两列m(x,y)。我想用三种不同的颜色生成一个散点图来反映 y 的值。因此,对于低于 y1 的所有 x,y 值(比如 1)我想要颜色 1,对于 y1 和 y2 之间的 x,y 值我想要颜色 2,最后对于高于 y2 的 y 值我想要拥有第三种颜色。我怎么能在 R 中实现这一点?

谢谢

4

2 回答 2

6

您可以使用 创建颜色级别cut,然后使用plot.

set.seed(1104)
x = rnorm(100)
y = rnorm(100)
colors = c("blue", "red", "green")
breaks = c(y1=0, y2=1)

# first plot (given breaks values)
y.col2 = as.character(cut(y, breaks=c(-Inf, breaks, Inf), labels=colors))
plot(x, y, col=y.col2, pch=19)

# second plot (given number of breaks)
y.col = as.character(cut(y, breaks=3, labels=colors))
plot(x, y, col=y.col, pch=19)

剧情

于 2013-06-29T01:26:23.103 回答
5

另一种选择是使用嵌套ifelse来定义颜色。

使用@Ricardo 数据:

dat <- data.frame(x = rnorm(100),y = rnorm(100))
with(dat,
plot(y~x, col=ifelse(y<y1,'red',
                     ifelse(y>y2,'blue','green')), pch=19))

在此处输入图像描述

于 2013-06-29T01:41:20.913 回答