This is probably not a duplicate as I am not requesting how to plot 2 series in the same plot, but rather how to add 2 (interconnected) y scales on one XY series
Here is the frame
t <- data.frame(x=seq(0,1,0.01), y=exp(seq(0,1,0.01))*500, y2=exp(seq(0,1,0.01))*30)
head(t)
x y y2
1 0.00 500.0000 30.00000
2 0.01 505.0251 30.30151
3 0.02 510.1007 30.60604
4 0.03 515.2273 30.91364
5 0.04 520.4054 31.22432
6 0.05 525.6355 31.53813
y and y2 are linearly interconnected. I would like to construct a plot with x, y (at left, side 2) and y2 (at right, side 4) so that each point on the plot has one x and 2 y coordinates.
base R only solutions please.
Thank you
From what I understand, you want
yandy2to correspond exactly (in terms of the scales)?In that case, you can plot y vs x which draws an axis on the left hand side, and then draw an identical axis on the right hand side, except that you change the labels.
In base graphics:
How this works:
1) plot y vs x. Doesn’t draw the axes, because:
2) we draw on the axes.
axis(2,pretty(range(t$y))).prettytakes a start and end point, and generates suitable axis tick marks (usually multiples of 5 or 10)3)
par(new=T): we tell R that the next plot it does should be drawn over the top of the current – don’t wipe away what we’ve drawn so far!4) we plot
y2vsx. This resets the coordinate system to they2coordinate system.5) we draw the right hand axis. This works because since we’ve just plotted
y2vsx, the coordinate system is fory2(and not foryas it was when we first started plotting).6) draw on the x axis
7) draw the box around the plot (if you like).
Tweaks
You may notice that the plot is lop-sided – there’s a lot more white space between the left hand side of the plot & the edge of the graphics device than there is on the right. That’s because R wants to make space for the y label which is usually drawn on the left.
If you want to even it up, use
par(mar=c(top,left,bottom,right)).Looking at
?par, we see the default isc(5,4,4,2)+.1.So, add this snippet to the front of your code:
Now you can see that there’s equal space either side of the plot, so ti doesn’t look lopsided any more. However, you may also notice that there is a y label on the left axis but not on the right.
It’s a bit ugly – we have to add it in manually using
mtext(which draws text on the plot):The
'y2'is the y axis label, the 4 means “draw on the right hand side of the plot”, andline=2says “draw the label on line 2, starting from 0 at the axis and counting outwards”.Summary