How to correctly use the color option in R image() function?
1
4
Entering edit mode
9.6 years ago
Xianjun ▴ 310

HI,

I got a question about how to assign color value in image() function. I thought the col option works as a vector with the same length of Z, with color of each cell in the matrix Z corresponding to the values in. However, it confused me with different result.

To make my question simple, let's say I want to make a color image for a vector x=1:4 with corresponding color for each cell.

x=1:4
image(1,1:length(x), matrix(x, nrow=1, ncol=length(x)), col=c("blue","red",'green','yellow'))

The output image looks like this:

output image 1

However, if I use a different x, say

x=c(3,1,2,1)
image(1,1:length(x), matrix(x, nrow=1, ncol=length(x)), col=c("blue","red",'green','yellow'))

I expected the color (from bottom to up) order should be green-->blue-->red-->blue, however, I got a very different order:

output image 2

I guess I misunderstand how to use the color option in the function. Can someone please help to advise? Thanks

-Xianjun

R image • 10k views
ADD COMMENT
2
Entering edit mode

This is interesting. If you receive the Yellow color from the end:

x=c(3,1,2,1)
image(1,1:length(x), matrix(x, nrow=1, ncol=length(x)), col=c("blue","red","green"))

it will color properly.

If you use 5 colors:

x=c(3,1,2,1)
image(1,1:length(x), matrix(x, nrow=1, ncol=length(x)), col=c("blue","red","green","yellow", "magenta"))

R will plot one color after other.

If you use 6 colors:

x=c(3,1,2,1)
image(1,1:length(x), matrix(x, nrow=1, ncol=length(x)), col=c("blue","red","green","yellow", "magenta", "grey"))

R will plot odd colors and then jump to last.

May be something with the algorithm?

ADD REPLY
0
Entering edit mode

Thanks for your comments, Deepak.

As my reply below, I guess I figured it out: We always get min(x)=col[1], max(x)=col[last]. For your case, then there are 6 colors, again, 1=blue, 3=grey, 2=green (since it's left close).

ADD REPLY
3
Entering edit mode
9.6 years ago
Xianjun ▴ 310

OK I figured it out myself:

Unless the breaks is set, the range of Z (or x in above example) is evenly cut into N intervals (where N = the length of color) and values in Z are proportionally assigned to the nearest color.

For example, when x=c(3,1,2,1) and col=c("blue","red",'green','yellow'), the minimal of x is assigned as the first color, and max to the last color. Any value between is calculated proportionally to a color. In this case, 2 is the the middle one, according to the principal that intervals are closed on the right and open on the left, it's assigned to "red". So, that's why we see the colors are yellow-->blue-->red-->blue.

ADD COMMENT

Login before adding your answer.

Traffic: 2210 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6