Adjust color scale of image plot in R

Viewed 7788

The image.plot function automatically generate the color scale for the inputs. For example,

library(fields)
x <- 1:10
y <- 1:15
z <- outer(x, y, "+")
image.plot(x, y, z)

will generate a figure like this enter image description here Now I want to adjust the color scale to the range from 0 to 20, and any values above 20 need to be colored the same as 20. So I added zlim=c(0,20) in the function parameters, and I get, enter image description here The problem is, although zlim adjusted the color scale range, the values above the limit were not assigned a color. How can I fix this? In this case, I want the up-right corner to be colored dark red i.e. to have the color assigned from the end of the color range.

3 Answers

Here is a slightly more complicated solution, which may allow for additional control of the scale axis:

library(sinkr) # https://github.com/marchtaylor/sinkr
x <- 1:10
y <- 1:15
z <- outer(x, y, "+")

ncolors <- 64
colors <- jetPal(ncolors)
zlim <- c(0,20)
breaks <- c(seq(zlim[1], zlim[2], length.out = ncolors), 1e6)


op <- par(no.readonly = TRUE)
layout(matrix(1:2,1,2), widths = c(4,1), heights = 4)
par(mar = c(4,4,1,1), cex = 1)
image(x, y, z, col = colors, breaks = breaks, zlim = zlim)
par(mar = c(4,0,1,4))
imageScale(z = z, ylim = zlim, zlim = zlim, col = colors, breaks = breaks, 
  axis.pos = 4)
par(op)

enter image description here

Here I show how you can specify the scale axis labels (e.g. the additions of a >):

# additional control
op <- par(no.readonly = TRUE)
layout(matrix(1:2,1,2), widths = c(4,1), heights = 4)
par(mar = c(4,4,1,1), cex = 1)
image(x, y, z, col = colors, breaks = breaks, zlim = zlim)
par(mar = c(4,0,1,4))
imageScale(z = z, ylim = zlim, zlim = zlim, col = colors, breaks = breaks, 
  axis.pos = 4, add.axis = FALSE)
axis(side = 4, at = seq(0,20,5), 
  labels = paste0(c(rep("", 4), ">"), seq(0,20,5)), las = 2)
mtext(text = "z", side = 4, line = 3)
par(op)

enter image description here

Related