在R中创建辅助y轴

时间:2016-03-10 00:07:27

标签: r histogram axis

我有一个关于在R中创建辅助y轴的问题。这是一个示例数据集

#generate some artifical data

per_cur <- runif(1171, 0.1, 7.62)
obs<-runif(1171,100,1000)

#create a density histogram of per_cur 

par(mfrow=c(2,1))
op <- par(mar = c(5,4,4,4) + 0.5)
hist(per_cur, prob=TRUE, border="white",main=NULL,las=1,cex.axis=0.8,ann = FALSE)
lines(density(per_cur), col="blue",lwd=2)

#add obs with a secondary y-axis

par(new = TRUE)
plot(per_cur,obs, cex=.5, pch=16, col=adjustcolor("black",alpha=0.2), axes = FALSE, ylab="Density")
axis(4,cex.axis=0.5)

它会生成一个情节,告诉我per_cur的分布,并显示我的关系 通过辅助y轴在per_curobs之间。但是,当我运行以下代码时,只有 我使用ylim=c(0,0.3)设置主y轴限制的差异你可以看到情节完全改变。 它给人的印象是obspre_cur之间的关系在两个图中都不同(更多obs个点     与第二个图相比,在第一个图中的曲线下。)

op <- par(mar = c(5,4,4,4) + 0.5)
hist(per_cur, prob=TRUE,ylim=c(0,0.3), border="white",main=NULL,las=1,cex.axis=0.8,ann = FALSE)
lines(density(per_cur), col="blue",lwd=2)
par(new = TRUE)
plot(per_cur,obs, cex=.5, pch=16, col=adjustcolor("black",alpha=0.2), axes = FALSE, ylab="Density")
axis(4,cex.axis=0.5)

我想问一下,当我调整主要y轴限制时,我的辅助y轴是否也有任何调整方式,以便 在两个图中曲线下都有相等数量的obs点。希望这很清楚。 enter image description here

1 个答案:

答案 0 :(得分:0)

这可以通过操纵每个图上的ylim来实现。例如:

#generate some artifical data

per_cur <- runif(1171, 0.1, 7.62)
obs<-runif(1171,100,1000)

#create a density histogram of per_cur 


# use these variables to set the limits on all plots
y1max = max(density(per_cur)$y)
y2max = max(obs)



par(mfrow=c(2,1))
op <- par(mar = c(5,4,4,4) + 0.5)
hist(per_cur, prob=TRUE, ylim = c(0, y1max), border="white",main=NULL,las=1,cex.axis=0.8,ann = FALSE)
lines(density(per_cur), col="blue",lwd=2)

#add obs with a secondary y-axis

par(new = TRUE)
plot(per_cur,obs, cex=.5, ylim = c(0, y2max), pch=16, col=adjustcolor("black",alpha=0.2), axes = FALSE, ylab="Density")
axis(4,cex.axis=0.5)

然后用相同的因子缩放每个轴:

# used to scale the axes
factor <- 2

op <- par(mar = c(5,4,4,4) + 0.5)
hist(per_cur, prob=TRUE, ylim = c(0, y1max * factor), border="white",main=NULL,las=1,cex.axis=0.8,ann = FALSE)
lines(density(per_cur), col="blue",lwd=2)
par(new = TRUE)
plot(per_cur,obs, cex=.5, ylim = c(0, y2max * factor),pch=16, col=adjustcolor("black",alpha=0.2), axes = FALSE, ylab="Density")
axis(4,cex.axis=0.5)

enter image description here