This is a follow-up of this question.
I wanted to plot multiple curves on the same graph but so that my new curves respect the same y-axis scale generated by the first curve.
Notice the following example:
y1 <- c(100, 200, 300, 400, 500) y2 <- c(1, 2, 3, 4, 5) x <- c(1, 2, 3, 4, 5) # first plot plot(x, y1) # second plot par(new = TRUE) plot(x, y2, axes = FALSE, xlab = "", ylab = "")
That actually plots both sets of values on the same coordinates of the graph (because I'm hiding the new y-axis that would be created with the second plot).
My question then is how to maintain the same y-axis scale when plotting the second graph.
(The typical method would be to use plot
just once to set up the limits, possibly to include the range of all series combined, and then to use points
and lines
to add the separate series.) To use plot
multiple times with par(new=TRUE)
you need to make sure that your first plot has a proper ylim
to accept the all series (and in another situation, you may need to also use the same strategy for xlim):
# first plot plot(x, y1, ylim=range(c(y1,y2))) # second plot EDIT: needs to have same ylim par(new = TRUE) plot(x, y2, ylim=range(c(y1,y2)), axes = FALSE, xlab = "", ylab = "")
This next code will do the task more compactly, by default you get numbers as points but the second one gives you typical R-type-"points":
matplot(x, cbind(y1,y2)) matplot(x, cbind(y1,y2), pch=1)
points
or lines
comes handy if
y2
is generated later, orx
but still should go into the same coordinate system.As your y
s share the same x
, you can also use matplot
:
matplot (x, cbind (y1, y2), pch = 19)
(without the pch
matplopt
will plot the column numbers of the y
matrix instead of dots).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With