简体   繁体   中英

Adjust color scale of image plot in R

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在此处输入图片说明 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, 在此处输入图片说明 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 ie to have the color assigned from the end of the color range.

You could use z[z > 20] <- 20 to achieve that with image.plot .

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

在此处输入图片说明

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)

在此处输入图片说明

Here I show how you can specify the scale axis labels (eg 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)

在此处输入图片说明

I manage to get one solution by using levelplot function from lattice package.

grid=expand.grid(x=x,y=y)
grid$z=as.vector(z)
levelplot(z~x*y,grid,at=c(seq(0,20,length.out = 50),Inf),col.regions = tim.colors(n = 64))

The result looks like,

在此处输入图片说明

However, I still wonder if this can be achieved by using image.plot or filled.contour. levelplot seems troublesome when I try to add a basic plot to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM