0

I am wondering whether I can color only certain cells in an R matrix using the

image

command. Currently, I am doing this:

library(Matrix)

args <- commandArgs(trailingOnly=TRUE)

csv_name <- args[1]
pdf_name <- args[2]

pdf(pdf_name)
data <- scan(csv_name, sep=",")
len <- length(data)
num <- sqrt(len)
matrix <- Matrix(data, nrow=num, ncol=num)
image(matrix)
dev.off()

The CSV file contains values between 0 and 1.
Executing the above code gives me the following image:

Matrix visulization

Now, I want to color in each row the six smallest values red. Does anyone have an idea how to achieve this?

Thanks in advance,
Sven

baptiste
  • 75,767
  • 19
  • 198
  • 294
Sven Hager
  • 3,144
  • 4
  • 24
  • 32
  • Do you mean "row" of the matrix or "row" in the image? From `?image`: "the x axis corresponds to row number and the y axis to column number ... i.e. a 90 degree counter-clockwise rotation" – BenBarnes Apr 27 '12 at 10:19
  • This is essentially the same. In my CSV file, I have N rows of N numbers, which will displayed in the file by an NxN matrix. – Sven Hager Apr 27 '12 at 10:26
  • Ach, sorry. `Matrix`, not `matrix`. – BenBarnes Apr 27 '12 at 10:29

2 Answers2

3

Matrix seems to use lattice (levelplot). You can add a layer on top,

m = Matrix(1:9, 3)
library(latticeExtra)
image(m) + layer(panel.levelplot(1:2,1:2,1:2,1:2, col.regions="red"))

Edit: actually, it makes more sense to give the colors in the first place,

levelplot(as.matrix(m), col.regions=c(rep("red", 6), "blue", "green", "yellow"), at=1:9)

but I haven't succeeded with image:

image(m, col.regions = c(rep("red", 6), "blue", "green", "yellow"), at=1:9)

I may have missed a fine point in the docs...

baptiste
  • 75,767
  • 19
  • 198
  • 294
0

You can also simply make another matrix where all values are NaN and then add a value of 1 to those that you want to highlight:

set.seed(1)
z <- matrix(rnorm(100), 10,10)
image(z)

z2 <- z*NaN
z2[order(z)[1:5]] <- 1
image(z2, add=TRUE, col=4)
Marc in the box
  • 11,769
  • 4
  • 47
  • 97