[R] plotting 2 Y-axes, aligning the 0 value
frederik at vanrenterghem.biz
Tue Dec 13 20:55:03 CET 2011
Being a novice to R, I would like to create a graph in R with 2 axes.
One of the 2 only has positive values, the other one also has negative
values. The part I'm struggling with is how to align the 2.
Rather than starting to plot the data from the x axis, I would like to
start plotting the positive values on the right axis only as of the 0
value on the left axis.
Using a simple example found online, I understand how to get 2 axis on
a single drawing, but I'm unsure how to accomplish the alignment
objective. In the example, the 0 value of the right axis should align
with the 0 of the left axis, and the red line should start in the
middle of the graph only, rather than at the bottom of it.
(This is an arbitrary example - the right axis could also start as of
value 1000, in which case I'd like 1000 to align with 0 of the left
# set up some fake test data
time <- seq(0,72,12)
betagal.abs <- c(0.05,-0.18,0.25,0.31,0.32,0.34,0.35)
cell.density <- c(0,1000,2000,3000,4000,5000,6000)
#add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 4) + 0.1)
# Plot first set of data and draw its axis
plot(time, betagal.abs, pch=16, axes=F, ylim=c(-1,1), xlab="",
ylab="", type="b",col="black", main="Mike's test data")
mtext("Beta Gal Absorbance",side=2,line=2.5)
# Allow a second plot on the same graph
# Plot the second plot and put axis scale on right
plot(time, cell.density, pch=15, xlab="", ylab="", ylim=c(0,7000),
axes=F, type="b", col="red")
axis(4, ylim=c(0,7000), col="red",col.axis="red")
# Draw the time axis
# Add Legend
Thanks in advance for any help you can provide!
More information about the R-help