[R] Plots with Y axis split into two scales

MacQueen, Don macqueen1 at llnl.gov
Wed Feb 26 21:01:03 CET 2014

Imagine you were plotting two sets, (x1, y1) and (x2, y2) on the same
plot, where x1 and x2 have the same range, but y1 and y2 need different
axis scales.

Here's an example that I think illustrates the idea. It's a long way from
being general, and if I were making it into a function in a package, I
would certainly find ways to parameterize the various y ranges.

But I think it illustrates a way to accomplish what was requested.

## some fake data
x <- 1:4
y <- c(1,105, 2, 130)

is.lo <- y < 100
x1 <- x[is.lo]
y1 <- y[is.lo]
x2 <- x[!is.lo]
y2 <- y[!is.lo]

yl1 <- c(0,10)
yl2 <- c(50,140)

ya1 <- c(0,5)
ya2 <- c(100,140)

par(mar=c(5.1, 4.1, 4.1, 4.1))

plot(range(x), yl1, type='n', yaxt='n', ylab='', xlab='X')
mtext('Low range of Y', side=2, line=2.5, adj=0.25)
axis(2, pretty(ya1))

par(new=TRUE)    ## this is the key "trick"

## I can now add data to the existing plot,
## using any data ranges I want

plot(range(x), yl2, type='n', yaxt='n', xaxt='n', ylab='', xlab='')
points(x2,y2, col='red')
axis(4, pretty(ya2))
mtext('High range of Y', side=4, line=2.5, adj=0.75)

One can build exactly what one wants using base R graphics tools.

(And I decline to address questions of whether such a plot is a good way
to present data)

Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550

On 2/25/14 9:18 AM, "David Parkhurst" <parkhurs at imap.iu.edu> wrote:

>I have a "Y" variable with many values less than 50, and many fewer
>between 50 and 250.I'd like to plot those Y's against an X, with two
>scales on the Y axis---maybe 60% of the axis height for 0-50 and the top
>40% for 50-250.(I can't use log(Y) because there are many zeroes, and
>that is the most desirable value.)
>I think I've seen plots done that way, but is there a way to create them
>in R?
>Thanks for any help.
>	[[alternative HTML version deleted]]
>R-help at r-project.org mailing list
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list