Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two plots with same X and Y axis

The plot shown is produced by the following R code.

png("test.png")
plot(data[,4],data[,3],type='l',col="green")
par(new=TRUE)
plot(data[,4],data[,2],type='l',col="red")
dev.off()

The range of Y-axis differs for both the plots and it is overwritten as shown in the image. Could someone help to set the same Y-axis range for both the plots.

enter image description here

like image 465
chas Avatar asked Apr 05 '13 13:04

chas


2 Answers

If the y scales largely overlap, then you can make an initial plot that includes the full range (without plotting anything on it) to define the axes, then plot the lines.

set.seed(5)
data <- data.frame(1:60, rnorm(60, 0.6, 0.1), rnorm(60, 0.65, 0.15), 
                   seq(2,120,by=2))

Using type='n' sets up the axes, but doesn't plot anything. using the range of all the data makes sure that the plot encompasses all the data.

plot(range(data[,4]), range(c(data[,3],data[,2])), type='n')
lines(data[,4], data[,3], type='l', col='green')
lines(data[,4], data[,2], type='l', col='red')

enter image description here

like image 130
Brian Diggs Avatar answered Sep 23 '22 04:09

Brian Diggs


You can use this method :

  1. draw the first plot
  2. call par(new=TRUE)
  3. draw the second plot on top of the first plot. The second plot does not draw default axes (axes=FALSE)

If the second plot has different y of the first one, you can use the axis() function to draw a secondary y-axis , at the right to represent the scale.

For example you can do something like this :

 data <- matrix(rnorm(4*100),ncol=4)
 par(mar=c(5, 6, 2, 4))
 plot(1:100,data[,3], lwd=3, col="green", ann=FALSE, las=2,type='l')
 mtext("I am at left", side=2, line=3.5)
 par(new=TRUE)
 plot(1:100,data[,2], ann=FALSE, axes=FALSE,col='red',type='l')
 mtext("I am at right)", side=4, line=2)
 title("Using par(new=TRUE) \n same X and different or not Y axis ")
 axis(4)

enter image description here

like image 20
agstudy Avatar answered Sep 23 '22 04:09

agstudy