Remi.b
Remi.b

Reputation: 18219

Fix the relation between color and value in `image(.)`

The two matrices m1 and m2 yield to the same image.

m1 = matrix(1:50, ncol=1)
m2 = matrix(seq(20, 30, length.out = 50), ncol=1)
image(m1, col=terrain.colors(100))
image(m2, col=terrain.colors(100))

enter image description here

That means that the relation between the values of the matrices and the color changes from plot to plot (and it totally makes sense). I'd like to keep this relation constant even if it it decreases the contrast within a single image. One solution is to add a "frame" to my matrices to force image to use the most extreme colors for the same extreme values.

min = min(cbind(m1, m2))
max = max(cbind(m1, m2))

m3 = rbind(max, m1 ,min)
image(m3, col=terrain.colors(100))

enter image description here

m4 = rbind(max, m2 ,min)
image(m4, col=terrain.colors(100))

enter image description here

It does the trick but it is ugly! I could make a slightly more advanced frame but the presence of the frame on the image will never be really desirable. Is there another solution?

Upvotes: 1

Views: 96

Answers (1)

NicE
NicE

Reputation: 21425

You can try to index the color vector by the values in your matrix. For example:

image(m1, col=terrain.colors(50)[m1]); 
image(m2, col=terrain.colors(50)[m2])

enter image description here terrain.colors(50) is a vector of 50 colors. Since m1 goes from 1 to 50 terrain.colors(50)[m1] will be equal to terrain.colors(50), and you will get colors 1 to 50.

m2 has decimal numbers from 20 to 30, if you give a decimal number as an index, the largest previous integer is used, so terrain.colors(50)[m2] will be a vector of colors between the twentieth and thirtieth colors of terrain.colors(50)

Upvotes: 1

Related Questions