Science11
Science11

Reputation: 883

r adjacent matrix plot with cell colors

I have a nxn dataframe as follows

        Col1    Col2    Col3    Col4    Col5    Col6
Col1    0       0       0       0       0       0
Col2    0       0       0       0       0       0
Col3    0      -2       3       1       1       1
Col4    0      -2       3       1       1       1
Col5    0       0       0       0       0       0
Col6    0      -2       3       1       1       1

I like to generate a plot with different colors for cells depending on their values. For example all cells with value 0 to be colored gray, all cells with value 1 to be colored blue, all cells with value -2 to be colored yellow, all cells with value 3 to be colored green.

Expecting a plot like this.

enter image description here

I am unclear how to generate such a plot. Any advice is much appreciated. Thanks.

Upvotes: 0

Views: 81

Answers (1)

Friede
Friede

Reputation: 7979

You could use {plot.matrix} for this:

x = read.table(text = "        Col1    Col2    Col3    Col4    Col5    Col6
Col1    0       0       0       0       0       0
Col2    0       0       0       0       0       0
Col3    0      -2       3       1       1       1
Col4    0      -2       3       1       1       1
Col5    0       0       0       0       0       0
Col6    0      -2       3       1       1       1", header = TRUE)
  
library("plot.matrix")
plot(as.matrix(x), main = "My coloured matrix",
     col = c("yellow", "grey", "lightblue", "lightgreen"), 
     key = NULL, digits = 0L, text.cell = list(cex = 1.5))

See the documentation and vignette for further details.

Upvotes: 3

Related Questions