如何使用 `image` 以常规布局显示矩阵?

How to use `image` to display a matrix in its conventional layout?

我有一个矩阵定义如下

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

然后 dataMatix 使用以下

绘制到屏幕上
image(1:10, 1:40, t(dataMatrix)[, nrow(dataMatrix):1])

谁能解释一下图像函数的第三个参数是如何工作的?我对 [] 内部发生的事情感到特别困惑。谢谢

没有什么比一个说明性的例子更好的了。考虑一个包含 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 是 "white")。您可以通过

查看非白色值
barplot(rep.int(1,8), col = 1:8, yaxt = "n")

如果在常规显示中绘制d,我们应该看到如下色块:

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

现在,让我们看看 image 会显示什么:

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

我们期望(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)

Em,好多了,不过好像行序颠倒了,所以想翻转一下。事实上,这样的翻转应该在 td 的列之间进行,因为 td:

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

是的,这就是我们想要的!我们现在有一个矩阵的常规显示。

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

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

这就是你现在拥有的。