[R] How to add a top X-axis with a different logarithmic scale?

Marc Schwartz MSchwartz at MedAnalytics.com
Thu Mar 25 22:29:56 CET 2004


On Thu, 2004-03-25 at 12:24, Itay Furman wrote:
> Hi,
> 
> I am trying to put on one plot two different logarithmic
> scales, using the bottom and top X-axes.
> Below there is an example of what I am trying to achieve,
> using axTicks() -- and fails.
> 
> I already spent few hours on that, and cannot figure out from
> ?par and ?axTicks what I am doing wrong.
> 
> Example follows:
> 
> ############################################################

See my interspersed comments and then code below:


> ####    Data
> x <- c(1.1*1:4, 25*1:5) / 50e+03
> y <- c(0.15*1:4, 0.6 + 0.05*1:5)
> 
> ####    Configure plot
> old.par <- par(no.readonly=TRUE)
> xlim <- range(xlim)

I presume the above line should be:

xlim <- range(x)

> ylim <- c(0, 1)
> 
> ####    Plot
> ## For production I will plot several data sets, so I first
> ## initialize window, and then use lines().
> plot.new()
> plot.window(xlim=xlim, ylim=ylim, log="x")
> lines(x, y)

Replace the above 3 lines with:

plot(x, y, type = "l", log = "x", xlim = xlim, ylim = ylim)

> ####    Plot axes
> axis(1)

The above axis(1) is unnecessary. The lower x axis is already created by
plot().

> ## Ticks for upper X-axis with a new scale: xlim*4e06
> cat("top.ticks:\n", top.ticks <- axTicks(3, usr=xlim*4e06),
>     "\n")

I am not sure if this is what you are trying to achieve, but use:

axis(3, labels = axTicks(3) * 4e06)

This will provide for the tick marks to be in their default locations,
just as with the lower 'x' axis, but the labels at each tick mark will
be adjusted based upon the 4e06. You do not need to change the axis
range to change the labels alone.


> ## Here I thought to put something like axis(3, at=top.ticks).
> ## Probably will need to rescale 'top.ticks' according to
> ## lower X-axis? 
> axis(2)

axis(2) is the left hand y axis and is not required here, since it too
is already drawn by plot().


> ### Restore
> par(old.par)
> 
> ############################################################
> 
> Thanks in advance for any comments/suggestions.
> 
> 	Itay


So, to follow up a bit more coherently, if I understand what you are
trying to do, the code should be:

x <- c(1.1 * 1:4, 25 * 1:5) / 50e+03
y <- c(0.15 * 1:4, 0.6 + 0.05 * 1:5)

old.par <- par(no.readonly=TRUE)
xlim <- range(x)
ylim <- c(0, 1)

plot(x, y, type = "l", log = "x", xlim = xlim, ylim = ylim)

axis(3, labels = axTicks(3) * 4e06)

par(old.par)



Does that get you what you want?

HTH,

Marc Schwartz




More information about the R-help mailing list