0

Simple question that I can't seem to find an answer for. Im trying to rotate a geom_raster plot from ggplot in R. Here's an example of what I mean:

Firstly, Im creating a matrix like so:

set.seed(1701)
a <- sample(1:10,100, replace=TRUE)
s <- matrix(a, nrow = 5, ncol=5)
s[upper.tri(s)] = t(s)[upper.tri(s)]
colnames(s)<- paste0("x", 1:5)
rownames(s)<- paste0("x", 1:5)
diag(s) <- 0
s 

Which produces this matrix, where the diagonals = 0 start from the top left:

   x1 x2 x3 x4 x5
x1  0  8  1  6 10
x2  8  0  7  1  7
x3  1  7  0  3  8
x4  6  1  3  0  9
x5 10  7  8  9  0

But when I plot it using:

ggplot(melt(s), aes(Var1,Var2, fill=value)) + geom_raster()

I get this: geom_raster() plot

How do I flip the the plot so the diagonals match the numerical matrix above? I have tried coord_flip() and scale_x_discrete(position = "top") but neither solve the problem.

Any suggestions? Thanks

Electrino
  • 2,636
  • 3
  • 18
  • 40
  • This has the effect of rotating the plot 90 degrees anticlockwise and reverses the x-axis order... I ideally need to keep the x-axis order the same (or rotate the plot 90 degrees clockwise) – Electrino Oct 22 '19 at 18:19

1 Answers1

3

There are several ways, but perhaps easiest is to reverse the factor levels of Var2, one way is with forcats::fct_rev:

ggplot(reshape2::melt(s), aes(Var1, forcats::fct_rev(Var2), fill=value)) + geom_raster()

See the duplicate target for some other options.

Axeman
  • 32,068
  • 8
  • 81
  • 94