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.
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')
You can use this method :
par(new=TRUE)
(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)
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