Tuesday, May 28, 2013

How to plot multiple graphs (scatter plots or histograms) on a same window in R?

Recently I have been working with R and bumped into different interesting facts of R. Here is how you can plot multiple graphs in the same window.

Your variable is x is a dependent variable on independent variables a, b, c and d. For example,

 a <- rnorm(100)
 b <- rnorm(100)
 c <- rnorm(100)
 d <- rnorm(100)


x <- a+b+c+d

If you want to understand how x is dependent upon each of these variables, you can make a scatter plot. If you want to see all these four dependency graphs on a same plot, you can use layout function in R.

Execute these commands..

M <- matrix(c(1:4), byrow=TRUE, nrow=2)
> layout(M)
> plot(x, a)
> plot(x, b)
> plot(x, c)
> plot(x, d)

Its that easy!

If you want to plot two histograms on a same plot, heres how you can do!


> hist1 <- hist(rnorm(500,3))
> hist2 <- hist(rnorm(500,5)) #500 random numbers centered around 5
> plot( hist1, col=rgb(0,0,1,1/4), xlim=c(0,10))  # first histogram
> plot( hist2, col=rgb(1,0,0,1/4), xlim=c(0,10), add=T)  # second histogram