2013-05-17 159 views
1

我有一个二维图。它上面的每个点都有一些值(如y),范围从01。我想用颜色在图上显示这些值。例如,如果任何点的值小于0.25,它应该是​​,其值在0.250.5之间的点将是yellow,其余的是red。如何在R中实现此目的。 以下是对(i,j)代表的各个点产生y的代码。如何在R中绘制颜色图

library(reldist) 
i <- 0 
for(i in seq(from=0, to=.8, by=0.1)){ 
j <- 0 
for(j in seq(from=0, to=1, by=0.1)){ 

a <- evalq(i*(1+i^2-i^2*j)/((1+i)^2*(1+i^2))) 
b <- evalq(i*(1-j)/(1+i)) 
c <- evalq(((1-j)/(1+i))-i*(1+i^2-i^2*j)/((1+i)^2*(1+i^2))) 

x <- c(a,b,c) 
y <- gini(x) # i want to plot y 
print(y) 

} 
} 
+0

如果你想绘制你的数据线,而不是点,你可以在'plotrix'使用'clplot'工具(免责声明 - 我写了那个工具)。 –

回答

1

尝试

plot(y , col = ifelse(y < 0.25 , 'green', ifelse(y < 0.5 , 'yellow' , 'red'))) 
1

您可以定义一个新的变量,指标的颜色要使用cut()功能。例如,

# I created an example i, j, and y rather than using your code for simplicity 
df <- expand.grid(i=seq(0, 0.8, 0.1), j=seq(0, 1, 0.1)) 
y <- runif(dim(df)[1]) 

# define the colors you want 
mycol <- c("green", "yellow", "red") 

# define a color index based on y using the breaks you want 
yindex <- cut(y, c(0, 0.25, 0.5, 1), labels=FALSE) 

# scatterplot using the specified colors 
plot(df$i, df$j, col=mycol[yindex]) 
0

使用outer将结果作为矩阵。它比for循环更容易。

i <- seq(from=0, to=.8, by=0.1) 
j <- seq(from=0, to=0.9, by=0.1) 

res <- outer(i,j,FUN=Vectorize(function(i,j) { 
    require(reldist) 
    a <- i*(1+i^2-i^2*j)/((1+i)^2*(1+i^2)) 
    b <- i*(1-j)/(1+i) 
    c <- ((1-j)/(1+i))-i*(1+i^2-i^2*j)/((1+i)^2*(1+i^2)) 
    gini(c(a,b,c)) 
}) 
) 

使用image密谋:

image(res, breaks = c(-1000,.25,.5,1000),col = c("green","yellow","red"), 
     axes=FALSE,xlab="i",ylab="j") 
axis(1, at = seq(0,1,length.out=length(i),labels=i) 
axis(2, at = seq(0,1,length.out=length(j),labels=j) 

enter image description here