2013-02-11 73 views
0

我有一些數據,我要繪製(例如plot(x,y)),但是我有一些標準,我想通過取決於矢量z看起來像c(1, 0, 1, 1, 1, 1, 0, NA ,0 ,0, .....)R:着色地塊

的值到顏色有什麼方法可以選擇1的顏色和0的顏色是什麼顏色?

感謝

+0

你想要什麼顏色將NAS是? – 2013-02-11 18:45:43

+0

還沒有決定,但爲了參數,讓我們說黑。如果我不想讓他們出現,該怎麼辦? – bdeonovic 2013-02-11 18:47:12

+0

用相同位置的顏色創建一個長度相同的矢量(例如用ifelse)並在圖中使用它 – Romain 2013-02-11 18:48:35

回答

3

你想,只要xy載體得到的顏色的載體,舉例如下:

z[is.na(z)] = 2 
zcol = c("red", "blue", "black")[z + 1] 

然後,你可以簡單地做:

plot(x, y, col=zcol) 
+0

我喜歡這個簡潔的答案:) – bdeonovic 2013-02-13 01:55:03

2

也許我錯過了一些東西,但我認爲你想要:

plot(x,y,col=ifelse(z==0,'zerocolour','onecolour')) 

其中你用redblue或其他什麼替換兩種顏色。

我不認爲NA將被繪製,所以你不必擔心這些。

對於更多的色彩,你可以創建一個小的映射data.framez的唯一值,再與data.frame合併z。下面是兩種顏色的例子:

map<-data.frame(z=c(0,1),col=c('red','blue')) 
plot(x,y,col=merge(z,map)$col) 
1

您可以提供的顏色向量參數col=,然後用Z選擇顏色。使用paste()到NA轉換爲字符,然後as.factor()解釋這些字符作爲1,2和3

x<-c(1,2,3,4,5) 
y<-c(1,2,3,4,5) 
z<-c(1,0,NA,1,1) 
plot(x,y,col=c("red","green",'black')[as.factor(paste(z))],pch=19,cex=3) 

str(as.factor(paste(z))) 
Factor w/ 3 levels "0","1","NA": 2 1 3 2 2 
2

使用GGPLOT2包

require(ggplot2) 

df <- data.frame(x = c(1, 2, 3, 4, 5), y = c(2, 3, 4, 6, 7), z = c(1, 0 , 1, 0 , NA)) 
df$z[is.na(df$z)] = 2 
ggplot(df, aes(x, y, color = as.factor(z))) + geom_point() 
4

我知道這已經回答了,但這裏是一些非常有直觀的代碼與一個繪圖供參考。

#Let's create some fictional data 
x = rbinom(100,1,.5) 
x[round(runif(10)*100)] = NA 

#Assign colors to 1's and 0's 
colors = rep(NA,length(x)) 
colors[x==1] = "blue" 
colors[x==0] = "red" 

#Plot the vector x 
plot(x,bg=colors,pch=21) 

enter image description here

+0

很好的例子+1 – mcheema 2013-03-22 12:42:49