Question: How to correctly use the color option in R image() function?
4
4.0 years ago by
Xianjun240
Great Boston Area
Xianjun240 wrote:

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:

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:

-Xianjun

R image • 5.9k views
modified 3.9 years ago • written 4.0 years ago by Xianjun240
2

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"))`

May be something with the algorithm. ?

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

3
3.9 years ago by
Xianjun240
Great Boston Area
Xianjun240 wrote:

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.