1

我有一个二维图。它上面的每个点都有一些值(比如y),范围从01。我想使用颜色在绘图上显示这些值。例如,如果任何点的值小于0.25应有的值,则green值介于0.25和之间的点0.5将为yellow,其余为red。如何在R. 以下是y为由 表示的各个点生成的代码(i,j)

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)

}
}
4

3 回答 3

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])
于 2013-05-17T12:45:41.710 回答
1

尝试

plot(y , col = ifelse(y < 0.25 , 'green', ifelse( y < 0.5 , 'yellow' , 'red')))
于 2013-05-17T12:36:29.893 回答
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)

在此处输入图像描述

于 2013-05-17T13:02:53.147 回答