ben
ben

Reputation: 799

How to move the vertical color strip legend in image.plot

Using image.plot from fields in R, I need to move the vertical color legend to the right a bit in order to accommodate a second y axis on the right hand side of the plot. Here is a reproducible example of what I'm talking about:

x <- seq(0, 1, 0.1)
y <- x
n <- length(x)
z <- matrix(runif(n^2), n, n)
xyzlist <- list(x, y, z)
image.plot(x,y,z)
yaxis2 <- y^2
axis(4, at = y, labels = yaxis2)

pic

So you see how the new axis labels crash into the legend. How to move the legend over so that it doesn't crash into the new axis labels?

Upvotes: 2

Views: 1912

Answers (1)

KoenV
KoenV

Reputation: 4283

You can toy around (to some extent) with the legend's size and location by using the argument smallplot of the function.

In your example, you could use the following code:

library(fields)
x <- seq(0, 1, 0.1)
y <- x
n <- length(x)
z <- matrix(runif(n^2), n, n)
xyzlist <- list(x, y, z)
yaxis2 <- y^2

### code added: left, right, bottom, top
image.plot(x,y,z, smallplot = c(.89, .94, .2, .8)) 
axis(4, at = y, labels = yaxis2)

This yields the following plot:

enter image description here

Of course, you can modify the legend further, making it smaller, shorter, etc

Please, let me know whether this is what you want.

Alternative

An alternative is to draw the plot 2 times. The first call generates a plot without the legend (because it is not well specified, and this generates an error). Then the axis is plotted (with a line adjustment, which may be different depending on the size of the plotting window). Thirdly and lastly, the legend is drawn (further to the left than in the previous plot with the error).

image.plot(x,y,z, smallplot = c(.85, .86, 1, .8)) 
axis(4, at = y, labels = yaxis2, line = -6)
image.plot(x,y,z, smallplot = c(.89, .92, .2, .8), legend.only = TRUE)

Upvotes: 2

Related Questions