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