2

I have trouble understanding the image function in R. I have the following matrix

         [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]     [,8]     [,9]    [,10]
[1,] 6.931799 7.092166 7.136029 6.735593 6.621951 6.740000 6.049774 6.162304 6.169014 5.626374
[2,] 7.942623 7.909091 9.923077 5.888889 8.647059 8.166667 6.625000 6.529412 7.571429 5.590643
[3,] 8.446237 6.800000 9.000000 9.631579 8.892857 7.083333 6.857143 6.250000 6.413793 5.491525
[4,] 7.698276 6.666667 8.833333 7.565217 9.100000 6.705882 6.421053 7.045455 6.045455 5.267857
[5,] 6.082524 8.300000 8.250000 8.777778 7.250000 7.928571 6.500000 6.920000 5.041667 4.970833
[6,] 6.128571 8.636364 7.300000 6.266667 7.500000 7.384615 6.727273 6.312500 5.638889 4.569231
[7,] 6.146739 7.000000 7.625000 6.615385 5.466667 5.941176 7.100000 6.687500 5.789474 4.479675
[8,] 5.403509 7.714286 6.500000 8.500000 6.384615 7.133333 6.294118 5.900000 5.615385 4.759804
[9,] 5.444444 5.666667 4.875000 6.200000 6.777778 6.166667 5.642857 6.222222 5.428571 4.385093
[10,] 5.186180 5.621118 5.004878 5.045016 4.875433 4.594340 4.260377 4.276382 4.205128 3.632721

and I would like to display it as an heatmap. To so so I use the image function as following

image(1:10,1:10,mat,axes=FALSE)

but the result is definitly not what is in my matrix!!![enter image description here]1

Any idea ? thanks

user1595929
  • 1,284
  • 3
  • 13
  • 23
  • Are you sure it is not right ... `image(1:10,1:10,mat,axes=FALSE) text(expand.grid(1:10, 1:10), labels=as.vector(round(mat,2)))` – user20650 Dec 22 '15 at 16:02
  • Check, use `fields` package to generate the legend.. `fields::image.plot(1:10,1:10,mat, col=heat.colors(12)) ; text(expand.grid(1:10, 1:10), labels=as.vector(round(mat,2)))` . Again looks okay?? – user20650 Dec 22 '15 at 16:04
  • Looks good to me, remember 1,1 is top left in your matrix but bottom left in your grid, so if you are simply overlaying them in your head it wouldn't look right. – Badger Dec 22 '15 at 16:09
  • `fortunes::fortune(143)` – Gregor Thomas Dec 22 '15 at 17:04
  • Possible duplicate: http://stackoverflow.com/q/31882079/903061 – Gregor Thomas Dec 22 '15 at 17:21

1 Answers1

3

Firstly, you should keep in mind that the matrix is printed from top left but plotted from bottom left, like Badger has said. Increasing the row index would move you to the right on the plot.

The color intensity increases from red to white.

Another thing that you might want to change is the range on your z value. The plot takes the min and max values from your matrix and sets that as the default range. However, you might want to add the following argument: zlim=c(0,10) , so that your range is from 0 to 10?

Lastly, if you want your plot to correspond to the locations of your z values in the matrix, you could create a new matrix where you rotate your original matrix by 90 degrees clockwise: t(apply(mat, 2, rev))

Stefan Mallia
  • 31
  • 1
  • 2