Sven Hager
Sven Hager

Reputation: 3194

R: color certain cells in Matrix

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

Upvotes: 0

Views: 1320

Answers (2)

Marc in the box
Marc in the box

Reputation: 11995

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)

Upvotes: 0

baptiste
baptiste

Reputation: 77096

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...

Upvotes: 3

Related Questions