Plotting axes with different scales for one data set in R

10,787

Solution 1

R doesn't seem to be rejecting your axes. What error are you getting? Your command will put ticks way off the graph (since it uses the first axis to position them). What I think you want is the following:

> plot(x = dataset$x, y = dataset$y)
> axis(4, at = axTicks(2), label = axTicks(2) * 10)

Solution 2

What you ask for is not always proper praxis, but you can force it via par(new=TRUE):

x <- 1:20
plot(x, log(x), type='l') 
par(new=TRUE)              # key: ask for new plot without erasing old
plot(x, sqrt(x), type='l', col='red', xlab="", yaxt="n")
axis(4)

The x-axsis is plotted twice, but as you have the same x-coordinates that is not problem. The second y-axis is suppressed and plotted on the right. But the labels show you that you are now mixing to different levels.

Share:
10,787
deontologician
Author by

deontologician

Updated on June 04, 2022

Comments

  • deontologician
    deontologician almost 2 years

    I have a large data set I am plotting in R, and I'd like to have an axis on each side of the graph show the data in two different scales. So for example, on the left vertical axis I'd like to plot the data directly (e.g. plot(y ~ x) ) and on the right axis, I'd like to have a linear scaling of the left axis. (e.g. plot( y*20 ~ x).

    So there would only be one data set displayed, but the axes would show different meanings for those data points.

    I've tried the following:

    plot(x = dataset$x, y = dataset$y)
    axis(4, pretty(dataset$y,10) )
    

    This will correctly print a new right axis with the same scale as the default left axis. (essentially useless, but it works) However, if I make this tiny change:

    plot(x = dataset$x, y = dataset$y)
    axis(4, pretty(10*dataset$y,10) )
    

    Suddenly, it refuses to add my new right axis. I suspect this has something to do with R seeing if the axis matches the data set in some way and rejecting it if not. How can I get R to ignore the data set and just print an arbitrary axis of my choosing?

  • Sharpie
    Sharpie about 14 years
    You could also use the argument axes=F in the second call to plot() to suppress the double plotting of the x-axis.
  • deontologician
    deontologician about 14 years
    This is perfect, solved my problem elegantly. My problem wasn't that the tick marks were being drawn wrong, it was that I needed to relabel them
  • philcolbourn
    philcolbourn over 13 years
    So at=axTicks(2) means get new axis ticks from the plot side=2; and label=axTicks(2)*10 means create labels from the 'at' ticks scaled by 10. Right?