user1357015
user1357015

Reputation: 11686

How to plot a "matrix" in a fixed grid pattern in R

I have a large data frame. A sample of the first 6 rows is below:

> temp
  M1 M2 M3 M4 M5 M6
1  1  1  1  1  1  1
2  1  1  1  1  1  1
3  0  1  0 -1  1  0
4  1  1  1  1  1  1
5  0  0  0 -1  0  1
6  0  0  0  0  0  0
> dput(temp)
structure(list(M1 = c(1, 1, 0, 1, 0, 0), M2 = c(1, 1, 1, 1, 0, 
0), M3 = c(1, 1, 0, 1, 0, 0), M4 = c(1, 1, -1, 1, -1, 0), M5 = c(1, 
1, 1, 1, 0, 0), M6 = c(1, 1, 0, 1, 1, 0)), .Names = c("M1", "M2", 
"M3", "M4", "M5", "M6"), row.names = c(NA, -6L), class = "data.frame")

The data frame only has values -1, 0 and 1. The total number of rows is 2,156. What I would like to do is to plot a a "grid" format where each row is comprised of 6 squares (one for each column). Each of the three values is then assigned a color (say, red, green, blue).

I've tried to do this with heatmap.2 (but I can't get the distinct squares to show up).

I've tried to do this using ggplot2 with geom_points() but can't figure out the best way to do it.

Any help on how to efficiently do this would be much appreciated!

Thanks!

Upvotes: 2

Views: 1824

Answers (3)

erasmortg
erasmortg

Reputation: 3278

Another option:

library(lattice)
temp <- as.matrix(temp)
levelplot(temp, col.regions= colorRampPalette(c("red","green","blue")))

This will produce the following plot:

enter image description here

Upvotes: 5

thothal
thothal

Reputation: 20329

You could use ggplot to do the following:

library(ggplot2)
dd <- expand.grid(x = 1:ncol(temp), y = 1:nrow(temp))
dd$col <- unlist(c(temp))
ggplot(dd, aes(x = x, y = y, fill = factor(col))) + geom_tile() 

enter image description here

Upvotes: 2

Heroka
Heroka

Reputation: 13139

I think geom_tile() is a better bet, in combination with reshaping to long.

library(ggplot2)
library(reshape2)

#assign an id to plot rows to y-axis
temp$id <- 1:nrow(temp)

#reshape to long
m_temp <- melt(temp, id.var="id")


p1 <- ggplot(m_temp, aes(x=variable,
                         y=id,fill=factor(value))) +
               geom_tile()

p1

enter image description here

Upvotes: 2

Related Questions