Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot two variables on y axis

Tags:

r

I've been trying to plot two variables on one y axis. Here is my code:

set.seed(20)
x1=rnorm(100)
x2=rnorm(100)
x3=rnorm(100)
t=data.frame(a=x1,b=x1+x2,c=x1+x2+x3)
plot(t$a,t$b,xlab="",ylab="",pch=0,col="red")
par(new=TRUE)
plot(t$a,t$c,xlab="a",ylab="b (blue) and c (red)",
col="blue",abline(c   (0,0),c (1,1),lty=5,col=320))

Because the two y axises use different scales there're two marks on the y axis. How do I modify my code? You help is very appreciated!

like image 458
Jade Avatar asked May 26 '26 09:05

Jade


1 Answers

You can use the same ylim range in both plots and they will look fine:

set.seed(20)
x1=rnorm(100)
x2=rnorm(100)
x3=rnorm(100)
t=data.frame(a=x1,b=x1+x2,c=x1+x2+x3)
#setting ylim below to the range -4 , 4
plot(t$a,t$b,xlab="",ylab="",pch=0,col="red", ylim=c(-4,4))
par(new=TRUE)
#doing it again here
plot(t$a,t$c,xlab="a",ylab="b (blue) and c (red)",
     col="blue",abline(c   (0,0),c (1,1),lty=5,col=320), ylim=c(-4,4))

Ouput:

enter image description here

like image 145
LyzandeR Avatar answered Jun 04 '26 23:06

LyzandeR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!