我有一个二维情节。它上的每个点都有一些值(例如,y
),范围从0
到1
。我想用颜色在图上显示这些值。例如,如果任何点的值小于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)
}
}
答案 0 :(得分:1)
尝试
plot(y , col = ifelse(y < 0.25 , 'green', ifelse( y < 0.5 , 'yellow' , 'red')))
答案 1 :(得分: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])
答案 2 :(得分: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)