对齐或缩放两个y轴:y1&;的零值;y2在R中应该正好相反

对齐或缩放两个y轴:y1&;的零值;y2在R中应该正好相反,r,plot,axis,par,R,Plot,Axis,Par,加载样本数据并绘制: x <- 1:5 y1 <- rnorm(5) y2 <- rnorm(5,20) par(mar=c(5,4,4,5)+.1) plot(x,y1,type="l",col="red") par(new=TRUE) plot(x, y2,,type="l",col="blue",xaxt="n",yaxt="n",xlab="",ylab="") axis(4) mtext("y2",side=4,line=3) legend("topleft",col

加载样本数据并绘制:

x <- 1:5
y1 <- rnorm(5)
y2 <- rnorm(5,20)
par(mar=c(5,4,4,5)+.1)
plot(x,y1,type="l",col="red")
par(new=TRUE)
plot(x, y2,,type="l",col="blue",xaxt="n",yaxt="n",xlab="",ylab="")
axis(4)
mtext("y2",side=4,line=3)
legend("topleft",col=c("red","blue"),lty=1,legend=c("y1","y2"))`

x下面列出的代码应适用于将两个y轴与基线对齐;但是,y1有奇怪的值,而不是0(在某些绘图中#记住我正在绘制80个双y轴绘图),这需要在我的算法中进行调整以设置y轴范围,否则绘图似乎正常。如果您发现原因或有任何澄清,请告诉我

rangeY1=range(df$y1, na.rm=TRUE, finite=TRUE)

rangeY2=range(df$y2, na.rm=TRUE, finite=TRUE)

# Scales of the given ranges
sumY1= rangeY1[2]-rangeY1[1]
sumY2= rangeY2[2]-rangeY2[1]
# Relative part of the positive and negative axis, only temporary variables
R=abs(rangeY1[1]/sumY1)
S=abs(rangeY2[1]/sumY2)
K=abs(rangeY1[2]/sumY1)
L=abs(rangeY2[2]/sumY2)
#Select new minimum values for the ranges
if(R>S){
  new_miny1=rangeY1[1]
  new_miny2=sumY2*rangeY1[1]/sumY1 }
if(S>R){
  new_miny1=sumY1*rangeY2[1]/sumY2
  new_miny2=rangeY2[1] }
if(S==R){
  new_miny1=rangeY1[1]
  new_miny2=rangeY2[1] }
#Select new maximum values for the ranges
if(K>L){
  new_maxy1=rangeY1[2]
  new_maxy2=sumY2*rangeY1[2]/sumY1 }
if(L>K){
  new_maxy1=sumY1*rangeY2[2]/sumY2
  new_maxy2=rangeY2[2] }
if(K==L){
  new_maxy1=rangeY1[2]
  new_maxy2=rangeY2[2] }
#"New ranges"
new_rangeY1=c(new_miny1, new_maxy1)
new_rangeY2=c(new_miny2, new_maxy2)