2016-11-29 68 views
1

我有一个矩阵定义为使用如下如何使用`image`在常规布局中显示矩阵?

dataMatrix <- matrix(rnorm(400), nrow=40) 

然后dataMatix被绘制到屏幕下面

image(1:10, 1:40, t(dataMatrix)[, nrow(dataMatrix):1]) 

有人可以解释图像功能的第三个参数是如何工作的?我对[]内发生的事情特别困惑。谢谢

回答

3

没有比示例更好的了。考虑8种元素的4 * 2整数矩阵:

d <- matrix(1:8, 4) 
#  [,1] [,2] 
#[1,] 1 5 
#[2,] 2 6 
#[3,] 3 7 
#[4,] 4 8 

如果我们image这个矩阵col = 1:8,我们将有颜色和像素之间的一对一的地图:彩色i用于遮阳像素具有值i。在R中,颜色可以用0到8的9个整数指定(其中0是“白色”)。如果d在传统的显示器绘制您可以通过

barplot(rep.int(1,8), col = 1:8, yaxt = "n") 

enter image description here

查看非白人的价值观,我们应该看到下面的色块:

black | cyan 
red | purple 
green | yellow 
blue | gray 

现在,我们来看看image会显示什么内容:

image(d, main = "default", col = 1:8) 

enter image description here

我们预计,(4行,2列)块显示屏,但我们得到了(2行,4列)显示。因此,我们要转d然后再试一次:

td <- t(d) 
#  [,1] [,2] [,3] [,4] 
#[1,] 1 2 3 4 
#[2,] 5 6 7 8 

image(td, main = "transpose", col = 1:8) 

enter image description here

EM,更好的,但似乎该行顺序是相反的,所以我们要甩掉它。

## reverse the order of columns 
image(td[, ncol(td):1], main = "transpose + flip", col = 1:8) 

enter image description here

是的,这就是我们想要的东西:其实,这样的翻转应的td列之间,因为有4列td进行!我们现在有一个传统的矩阵显示器。

注意ncol(td)只是nrow(d),并td只是t(d),所以我们也可以这样写:

image(t(d)[, nrow(d):1]) 

这是你有什么权利了。

+0

啊哈!所以 [,ncol(td):1]#是列 和 [nrow(td):1,]#是行 – David

+0

@李,非常感谢你,非常清楚。我会很乐意参考文档;-) – David

+0

@ Li。完成!找到了 ! – David