Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop ggplot2 from rotating my matrix 90 degrees?

Tags:

r

ggplot2

heatmap

I'm trying to create a heatmap using ggplot2, but I noticed that it seems to rotate the matrix 90 degrees to the left when I plot it. It's very strange, and using coord_flip() and t() don't work, because they rotate it to the left, not the right (so rather than correcting, they create a heatmap that is rotated 180 degrees). Are there any options or tricks to prevent this? Here is the relevant code:

#this is needed to run custHeat
zeroInterval <- function(mat, colors){
  #modified version of findInterval such that zero is given its own category
  #This function takes intervals as left exclusive, right inclusive.
  #This is mostly so that intervals consisting of a single value will still be represented.
  intervalMat <- matrix(0, nrow=nrow(mat), ncol=ncol(mat))
  j <- 1
  for(i in 1:(length(colors) - 1)){
    if(colors[i] != colors[i+1]){
      intervalMat[mat>colors[i] & mat<=colors[i+1]] <- j
      j <- j + 1
    } else {
      intervalMat[mat==colors[i]] <- j
      j <- j + 1
    }
  }
  return(intervalMat)
}

#this actually plots the heatmap
custHeat <- function(M){

  #create color bins/ranges for skewed matrix
  color_bins <- c(-5, -4, -3, -2, -1, 0, 0, 1)
  colors <- c('#67001F', '#B2182B', '#D6604D', '#F4A582', '#FDDBC7', "#FFFFFF", '#C6DBEF')

  #create complete color palette
  color_palette <- colorRampPalette(colors)(length(color_bins) - 1)

  #This function assigns a number to each matrix value, so that it is colored correctly
  mod_mat <- zeroInterval(random_matrix, color_bins)


  ## remove background and axis from plot
  theme_change <- theme(
    plot.background = element_blank(),
    panel.grid.minor = element_blank(),
    panel.grid.major = element_blank(),
    panel.background = element_blank(),
    panel.border = element_blank(),
    axis.line = element_blank(),
    axis.ticks = element_blank(),
    axis.text.x = element_blank(),
    axis.text.y = element_blank(),
    axis.title.x = element_blank(),
    axis.title.y = element_blank()
  )

  ## output the graphics
  ggplot(melt(mod_mat), aes(x = X1, y = X2, fill = factor(value))) +
    geom_tile(color = "black") +
    scale_fill_manual(values = color_palette, name = "") +
    theme_change
}

##create random matrix, skewed toward negative values
random_matrix <- matrix(runif(100, min = -5, max = 1), nrow = 10)
random_matrix[1,] <- 0 #zeros should be at the top row of the heatmap
custHeat(random_matrix)
like image 854
Eli Sander Avatar asked Jan 28 '13 23:01

Eli Sander


People also ask

How do I change the orientation of a matrix in R?

Rotating or transposing R objects frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command. The result of the t() command is always a matrix object.

How do you rotate a 90 degree clockwise matrix?

Rotate Matrix 90 Degree Clockwise or Right Rotation The rotation of a matrix involves two steps: First, find the transpose of the given matrix. Swap the elements of the first column with the last column (if the matrix is of 3*3). The second column remains the same.

How do you rotate a matrix 90 degrees anticlockwise in Java?

Approach to solve this problem Take Input of a square matrix. Find the transpose of the matrix. Swap the element at index 0 with index n-1. Return the output.


1 Answers

You can counteract the 90 degree counter-clockwise rotation of the plotting function by pre-rotating your matrix 90 degrees in the other direction:

## An example matrix
(m <- matrix(1:9, ncol=3))
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9

## The same matrix rotated 90 degrees clockwise
t(m)[,nrow(m):1]
#      [,1] [,2] [,3]
# [1,]    3    2    1
# [2,]    6    5    4
# [3,]    9    8    7

Added later:

Some R plotting functions use the same convention as image(), while others do not. (Please feel free to add to this list.)

m <- matrix(1:9, ncol=3)


## ------- These plotting functions DO rotate a matrix --------

## image()
image(m, col=blues9)

## levelplot() -- a lattice equivalent of image()
library(lattice)    
levelplot(m, at=(1:10)-0.5, col.regions=blues9)

## Others
contour(m)
filled.contour(m, color=colorRampPalette(blues9))
persp(m) 
lattice::contourplot(m)
lattice::wireframe(m)  ## Nicely illustrates the logic of the indexing it uses


## ------- These plotting functions DO NOT --------

## imageRaster() -- a graphical primitive used by image(), among other functions 
plot(0:1, 0:1, type="n", xlab="", ylab="")
rasterImage(matrix(blues9, ncol=3), 0,0,1,1, interpolate=FALSE)

## grid.raster() -- imageRaster()'s counterpart in the grid graphical system
library(grid)
grid.raster(matrix(blues9, ncol=3), interpolate=FALSE)

## plot(raster()) in raster package
library(raster)
plot(raster(m), col=blues9)
like image 192
Josh O'Brien Avatar answered Sep 23 '22 17:09

Josh O'Brien