Brtx - 1 year ago 72
R Question

# r - aligning x-axis image and base plot

When I try to align an image plot with a xy plot by their x-axis there is a small misalignment between the x-values. Can't figure out how to get rid of it!
Notice the misalignment of the vertical lines from the bottom plot with the x-axis on the top plot.

``````par(mfrow=c(2,1))
par(mar=c(0,5,5,5))
image(x=1:100,z=replicate(10, rnorm(100)))
par(mar=c(5,5,0,5))
par(xaxs="i")
plot(1:100,rnorm(100))
abline(v=1:100)
``````

Gurus, help!! Thank you!!

PS: Could not figure it out with the post "plot-time-series-and-image-in-r-so-that-x-axis-labels-line-up-perfectly", still having issues!

The problem is that `image` draws data as a grid of cells which have a given width. If the length of `x` in `image` equals to `nrow(z)` then it specifies the midpoints of the cells. In your example this gives you rectangles centered around 1:100, effectively resulting in the x-axis covering the range from `0.5` to `100.5`, which gives the observed misalignment.

In order to match the ranges in both plots you need to specify `xlim` to `plot` accordingly. In the following example I use `n = 10` to make things more obvious.

``````par(mfrow=c(2,1))
par(mar=c(0,5,5,5))
image(x=1:n,z=replicate(10, rnorm(n)))
par(mar=c(5,5,0,5))
par(xaxs="i")
plot(1:n,rnorm(n), xlim=c(.5,n+.5))
abline(v=1:n)
``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download