使用'if'语句限制的散点图

时间:2013-12-03 21:36:17

标签: r plot

我很难尝试这种策划,我希望你能帮忙。

我目前有矩阵:

hello <- matrix(0:2, nrow=30, ncol=30)

我想仅在hello == 1

时从x和y绘制点
x <- sample(5:25, 25,replace=TRUE)
y <- sample(5:25, 25,replace=TRUE)

我目前正在尝试使用&#39; if&#39;声明限制了绘图区域,到目前为止还没有成功。正如您所看到的,如果您绘制它,这些点仍然是随机分布的。

我的代码如下:

hello <- matrix(0:1, nrow=30, ncol=30)
    if (hello[i,j]==1)
    {
      x <- sample(5:25, 25,replace=TRUE) 
      y <- sample(5:25, 25,replace=TRUE)
    }
    plot(1:30, 1:30, type="n")
    image(1:nrow(hello), 1:ncol(hello), hello, col=c("white", "yellow"))
      #visualize 1 and 0s
    points(x,y, col="green")
  }
}

*编辑:摆脱for循环

1 个答案:

答案 0 :(得分:2)

我实际上很难弄明白你想做什么:

假设......:

  • ...你有一个以hello保存的网格,用于存储有效点的信息用于绘图(hello [1,2]存储有效绘制坐标x = 2和y = 1的信息)
  • ......可能的绘图候选对象是x和y

...比这可能是答案,试一试:

# gen data
x <- 1:30
y <- 1:30
hello <- matrix(0:1, nrow=30, ncol=30)

# make basic plot of hello matrix
image(  1:ncol(hello), 1:nrow(hello), 
        t(hello), col=ifelse(t(hello)==1,"yellow","white"),
        ylab="rows",xlab="columns"      )
box()

# now let's decide whether or not a coordinate should be plotted, 
# depending on the value of hello for this coordinate ...
# by cycling through each pair of coordinates and saving T/F in iffer
iffer <- NULL
for(i in seq_along(x)) iffer <- c( iffer, hello[ y[i] , x[i] ]==1 )

# plotting of the adequate subset of points that had a hello value of 1 
points( x[iffer] , y[iffer], col="green")

enter image description here