Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpectedly transposed flipped output from R "image" function

Say I have a matrix:

m<-matrix(1:5,4,5)
m
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    4    3    2
[2,]    2    1    5    4    3
[3,]    3    2    1    5    4
[4,]    4    3    2    1    5

Now, when I do

image(m)

I get unexpected output. And so I need to do:

image(t(m)[,4:1])

to get it the "right" way. What is the point?

like image 516
danas.zuokas Avatar asked Dec 17 '22 01:12

danas.zuokas


2 Answers

Others have pointed out that what you are seeing is consistent with the documentation, here are a couple of thoughts of the why it does it that way.

The image function was not originally designed to plot images/graphics, but to represent tabular information graphically, therefore the ordering of things was intended to be consistent with other graphing ideals rather than making sure that clipart looked correct. This means that rotations and mirroring of the image does not make it "wrong", it is just a different view, and the view that followed the plotting rules was chosen.

It also tried to be consistent with other graphing functions and the philosophy that they were based on. For a scatter plot we use plot(x,y) with x being the horizontal axis, but when we do table(x,y) the x variable forms the rows of the resulting table. Both of these facts are consistent with common practice (the explanatory variable is generally the row variable in a table since numbers are easier to compare vertically). So the image function uses the rows of the matrix (the x variable if it came from the table function) as the predictor/explanatory variable on the horizontal axis. It is also customary for values in plots to increase going left to right and bottom to top (but in tables it is more common to increase going top to bottom).

like image 130
Greg Snow Avatar answered Apr 07 '23 08:04

Greg Snow


From the help file:

Notice that image interprets the z matrix as a table of f(x[i], y[j]) values, so that the x axis corresponds to row number and the y axis to column number, with column 1 at the bottom, i.e. a 90 degree counter-clockwise rotation of the conventional printed layout of a matrix.

like image 22
Sacha Epskamp Avatar answered Apr 07 '23 10:04

Sacha Epskamp