Plot two graphs on the same plot in R

r
datavisualization

#1

Hi,

I want to plot two graphs on the same plot in R. IN MATLAB we can use the ‘hold on’ command to do so.
How to do this in R?

I used this code->

plot(l,col=‘green’,type=‘l’)
par(new=TRUE)
plot(k,col=‘red’,type=‘l’)

but I am getting a graph like this->

The two graphs overlap and so do their markings and labels on the y axes. How to plot them on the same scale of x and y axes?
Thanks.


#2

Hi @pravin,

You can do something like this ->

plot(l,col=‘green’,type=‘l’,ylim=range(c(0,1.5)))
par(new=TRUE)
plot(k,col=‘red’,type=‘l’,ylim=range(c(0,1.5)))

You need to specify the limits for the y axes for one plot in such a way as to make sure that it can accept the next series (and in another situation you may need to also use the same strategy for xlim):

You may adjust the limits according to your needs.

Hope it helps.


#3

It works fine after using ylim. I now want to save the current graph displayed in the graphics device into a variable so that i can use the graph somewhere else.
Is there a way to do that other than having to take a snapshot to do it?