Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the order in which a matrix is plotted in R?

I want to plot an image in matrix form. The image is ordered in such a way that the values need to be plotted from top left to bottom right. However, when I try to plot it (in either base R, or using ggplot), the values are not plotted on the locations where I expect them.

Here’s what a sample matrix looks like in base R:

A <- matrix(c(1,2,2,2,3,4),byrow=T,nrow=2)
A
image(A)

So I would want the values to be plotted as (from top left to bottom right): 1-2-2 (top row), 2-3-4 (bottom row). If you plot it in base R using the image function, the matrix is plotted in three rows, by seemingly transposing rows and columns?
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I try the ggplot approach using geom_raster (below), rows and columns are no longer transposed, but the top row is plotted on the bottom.

longData <- reshape2::melt(A)
ggplot(longData,aes(x=Var2,y=Var1))+
  geom_raster(aes(fill=as.factor(value)))

enter image description here

How can I fix this so that the first row of my matrix is plotted from the top left to top right and so on?

>Solution :

I think best is to flip and/or transpose the Matrix (both base R and ggplot are of course drawing from bottom left first, which is field "1/1".

library(ggplot2)
A <- matrix(c(1,2,2,2,3,4),byrow=T,nrow=2)

## base R: use the transposed flipped Matrix
image(t(A[nrow(A):1, ]))


## ggplot2: use the flipped Matrix
longData <- reshape2::melt(A[nrow(A):1, ])
ggplot(longData,aes(x=Var2,y=Var1))+
  geom_raster(aes(fill=as.factor(value)))

Created on 2023-02-22 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading