user1830307
user1830307

Reputation:

Creating a matrix by color in R

Say I have created a test matrix 4*4 matrix:

varieties = c("A", "B", "C", "D")
matVar = matrix(c(1,5,3,4,8,5,2,8,9,4,6,5,3,7,3,2), nrow = length(varieties), ncol = length(varieties))

I have a matrix that looks as follows:

     [,1] [,2] [,3] [,4]
[1,]    1    8    9    3
[2,]    5    5    4    7
[3,]    3    2    6    3
[4,]    4    8    5    2

How can I create a heatmap image in R such that the rows and columns are named the varieties (A, B, C, D), and the color is graded by the value between that combination of varieties?

I have tried the following:

library(reshape2)
library(ggplot2)
tdm <- melt(matVar)

ggplot(tdm, aes(x = varieties, y = varieties, fill = factor(value))) +
  labs(x = "Variety", y = "Variety", fill = "Value") +
  geom_raster()

And get the error:

Error: Aesthetics must either be length one, or the same length as the dataProblems:varieties, varieties

Any advice is appreciated!

Upvotes: 0

Views: 1880

Answers (2)

jlhoward
jlhoward

Reputation: 59355

Something like this?

enter image description here

library(reshape2)
library(ggplot2)
df <- data.frame(id=varieties,matVar)
colnames(df)[2:ncol(df)] <- varieties
gg <- melt(df, id="id")
ggplot(gg, aes(x=id,y=variable,fill=value))+
  geom_tile()+
  scale_fill_gradient(low="#FFFF88",high="#FF0000")+
  coord_fixed()

Notes:

  1. coord_fixed() is used so the tiles are square.
  2. scale_fill_gradient(...) is used to set the fill colors to yellow - red. Look at the documentation for scale_fill_gradientn(...) and scale_fill_gradient2(...) for other options.

Upvotes: 3

mmk
mmk

Reputation: 514

The values passed to aes() need to match the column names in your data table -- in this case, use Var1 and Var2 (the default variable names generated by melt()) instead of variables:

ggplot(tdm, aes(x = Var1, y = Var2, fill = factor(value)) +
  labs(x = "Variety", y = "Variety", fill = "Value") +
  geom_raster()

If you want a continuous color gradient instead of discrete colors, just use value instead of factor(value).

Upvotes: 0

Related Questions