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

自作多情 提交于 2019-12-19 11:32:10

问题


I have a matrix defined as follows

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

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


回答1:


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

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")

If d is plotted in conventional display, we should see the following colour blocks:

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

Now, let's see what image would display:

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

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, 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.

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.



来源:https://stackoverflow.com/questions/40855713/how-to-use-image-to-display-a-matrix-in-its-conventional-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!