Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading