quibble
quibble

Reputation: 337

color assignment using the image function

I want specific numbers and specific colors to be associated in plots.

The following code

z <- matrix(1:5, 5, 5)
image(z, col=c("red","blue","pink","yellow","black"))

produces the plot I want,

enter image description here

but

z[z < 4] <- 4
image(z,col=c("red","blue","pink","yellow","black"))

will assign "red" to number 4.

enter image description here

I want the color assignment to stay the same.

Upvotes: 1

Views: 394

Answers (1)

Darren Tsai
Darren Tsai

Reputation: 35604

Solution 1

The argument breaks indicates breakpoints for the colors and must have one more breakpoint than color and be in increasing order.

image(z, col = c("red", "blue", "pink", "yellow", "black"), breaks = 0:5)

The code above means to map the values within

  • ( 0, 1 ] to red
  • ( 1, 2 ] to blue
  • ( 2, 3 ] to pink
  • ( 3, 4 ] to yellow
  • ( 4, 5 ] to black


Solution 2

Use indices of colors.

color <- c("red","blue","pink","yellow","black")
image(z, col = color[z])

Upvotes: 2

Related Questions