2013-06-29 129 views
2

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

感谢

回答

5

您可以使用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) 

theplot

+0

谢谢,这是真正的帮助! – user2533698

3

另一种选择是使用嵌套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)) 

enter image description here