Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting multiple curves same graph and same scale

Tags:

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.

like image 493
Renan Avatar asked Jul 28 '11 01:07

Renan


2 Answers

(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 = "") 

enter image description here

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) 
like image 159
IRTFM Avatar answered Nov 03 '22 05:11

IRTFM


points or lines comes handy if

  • y2 is generated later, or
  • the new data does not have the same x but still should go into the same coordinate system.

As your ys share the same x, you can also use matplot:

matplot (x, cbind (y1, y2), pch = 19) 

matplot (x, cbind (y1, y2), pch = 19)

(without the pch matplopt will plot the column numbers of the y matrix instead of dots).

like image 28
cbeleites unhappy with SX Avatar answered Nov 03 '22 03:11

cbeleites unhappy with SX