2013-06-29 213 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