Mike
Mike

Reputation: 1069

R: Creating graphs with two y-axes

I'm looking to display two graphs on the same plot in R where the two graphs have vastly different scales i.e. the one goes from -0.001 to 0.0001 and the other goes from 0.05 to 0.2.

I've found this link http://www.statmethods.net/advgraphs/axes.html

which indicates how to display two y axes on the same plot, but I'm having trouble.
My code reads as follows:

      plot(rateOfChangeMS[,1],type="l",ylim=c(-0.01,.2),axes = F)
      lines(ratios[,1])
      x = seq(-0.001,0.0001,0.0001)
      x2 = seq(0.05,0.2,0.01)
      axis(2,x)
      axis(4,x2) 

The problem I'm having is that, although R shows both axes, they are not next to each other as I would like, with the resulting graph attached. The left axis is measuring the graph with the small range, while the right is measuring the graph from 0.05 to 0.2. The second graph is, in fact, on the plot, but the scaling is so small that you can't see it.

Not sure if there is some etiquette rule I'm violating, never uploaded an image before so not quite sure how best to do it.

Any help would be greatly appreciated!

Thanks

Mike

Incorrect Axis measurement

Upvotes: 1

Views: 3144

Answers (1)

jlhoward
jlhoward

Reputation: 59355

Since you don't provide a reproducible example, or a representative dataset, this is a partial answer.

set.seed(1)
df <- data.frame(x=1:100, 
                 y1=-0.001+0.002/(1:100)+rnorm(100,0,5e-5),
                 y2=0.05+0.0015*(0:99)+rnorm(100,0,1e-2))

ticks.1 <- seq(-0.001,0.001,0.0001)
ticks.2 <- seq(0.05,0.2,0.01)

plot(df$x, df$y1, type="l", yaxt="n", xlab="X", ylab="", col="blue")
axis(2, at=ticks.1, col.ticks="blue", col.axis="blue")
par(new=T)
plot(df$x, df$y2, type="l", yaxt="n", xlab="", ylab="", col="red")
axis(4, at=ticks.2, col.ticks="red", col.axis="red")

The reason your left axis is compressed is that both axes are on the same scale. You can get around that by basically superimposing two completely different plots (which is what having two axes does, after all). Incidentally, dual axes like this is not a good way to visualize data. It creates a grossly misleading visual impression.

Upvotes: 3

Related Questions