Daan
Daan

Reputation: 357

How can I fix colors for the numbers in a matrix

Currently I try to make multiple visualizations in which the numbers in a matrix must get a certain (fixed) color in an image.

Due to the fact that I cannot find a way to really assign a color to a fixed number this causes me more trouble than I had thought.

The problem shows in the following examples:

Say we define the following colors to be associated with the following numbers

cols <- c(
 '0' = "#FFFFFF",
 '1' = "#99FF66",
 '2' = "#66FF33",
 '3' = "#33CC00",
 '4' = "#009900" 
)
image(as.matrix(d), col=cols)

Now if we visualise the following matrix all seems good

d<-read.table(text="
0  1  0  3
3  2  1  4
4  1  0  2
3  3  0  1")
image(as.matrix(d), col=cols)

However if a visualise the following matrix the problem becomes clear

d<-read.table(text="
1  1  1  3
3  2  1  4
4  1  2  2
3  3  2  1")

image(as.matrix(d), col=cols)

We should be skipping white ("#FFFFFF") as the number 0 is not present. However R chooses to use white ("#FFFFFF") anyhow and asociate that with the number 1 skipping "#009900" instead.

For the consistency of my visualizations it is rather important that colors remain associated with the same numbers for all images, so how can I implement this?

Upvotes: 2

Views: 57

Answers (2)

Daan
Daan

Reputation: 357

Thanks to Andre's advice I can solve it in a rather neat fashion

d<-as.matrix(read.table(text="
1  1  1  3
3  2  1  4
4  1  1  2
3  3  1  1"))

cols <- c(
'0' = "#FFFFFF",
'1' = "#99FF66",
'2' = "#66FF33",
'3' = "#33CC00",
'4' = "#009900"
)

image(as.matrix(d), col= cols[ names(cols) %in% d ])

Upvotes: 0

Andre Elrico
Andre Elrico

Reputation: 11480

remove the color values that are not prominent in your matrix:

image(as.matrix(d), col=cols[names(cols)%in%unlist(d)])

unlist works only on lists as the name tells. If d is already a matrix simply use c(d)

Upvotes: 3

Related Questions