如何使用`image`以常规布局显示矩阵? [英] How to use `image` to display a matrix in its conventional layout?
问题描述
我有一个定义如下的矩阵
I have a matrix defined as follows
dataMatrix <- matrix(rnorm(400), nrow=40)
然后 dataMatix
使用以下方式绘制到屏幕上关注
then dataMatix
is plotted to the screen using the following
image(1:10, 1:40, t(dataMatrix)[, nrow(dataMatrix):1])
有人可以解释图像函数的第三个参数是如何工作的吗?我对 []
内发生的事情感到特别困惑。谢谢
can someone explain how the third argument of the image function works ? I'm particularly confused by what happens inside []
. Thanks
推荐答案
没有比说明性的例子更好的了。考虑一个 4 * 2
8个元素的整数矩阵:
There is nothing better than an illustrative example. Consider a 4 * 2
integer matrix of 8 elements:
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是白色)。您可以按
If we image
this matrix with col = 1:8
, we will have a one-to-one map between colour and pixel: colour i
is used to shade pixel with value i
. In R, colours can be specified with 9 integers from 0 to 8 (where 0 is "white"). You can view non-white values by
barplot(rep.int(1,8), col = 1:8, yaxt = "n")
如果 d
在常规显示中绘制,我们应该会看到以下颜色块:
If d
is plotted in conventional display, we should see the following colour blocks:
black | cyan
red | purple
green | yellow
blue | gray
现在,让我们看看图像
将显示:
image(d, main = "default", col = 1:8)
我们期待一个(4行,2列)块显示,但我们得到一个(2行,4列)显示。所以我们想转置 d
然后再试一次:
We expect a (4 row, 2 column) block display, but we get a (2 row, 4 column) display. So we want to transpose d
then try again:
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列:
Em, better, but it seems that the row ordering is reversed, so we want to flip it. In fact, such flipping should be performed between columns of td
because there are 4 columns for td
:
## reverse the order of columns
image(td[, ncol(td):1], main = "transpose + flip", col = 1:8)
是的,这就是我们想要的!我们现在有一个传统的矩阵显示器。
Yep, this is what we want! We now have a conventional display for matrix.
注意 ncol(td)
只是 nrow(d)
, td
只是 t(d)
,所以我们也可写:
Note that ncol(td)
is just nrow(d)
, and td
is just t(d)
, so we may also write:
image(t(d)[, nrow(d):1])
这就是你现在所拥有的。
which is what you have right now.
这篇关于如何使用`image`以常规布局显示矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!