[英]Plot ecdf and density into same graph with differing y-axis
Consider the two following plots: 考虑以下两个图:
x <- rnorm(1000, sd=10)
plot(density(x))
plot(ecdf(x))
Please note the different y-axis ranges: 请注意不同的y轴范围:
Now I would like to have these two in one graph and two y-axis. 现在,我想在一张图表和两个y轴中包含这两个。
I know the basics ( add=TRUE
, or par(new=TRUE)
), but add=TRUE
does not work due to the different scales, par(new=TRUE)
requires specifying a x-axis to avoid over plotting. 我知道一些基础知识(
add=TRUE
或par(new=TRUE)
),但由于比例不同, add=TRUE
不起作用, par(new=TRUE)
需要指定x轴以避免过度绘制。
Is there an easy way of getting these two into one graph, left y-axis density, right y-axis ecdf? 是否有一种简单的方法将这两个图表(左y轴密度,右y轴ecdf)合为一个图?
Create plots with two different Y scales is not generally recommended, but the easiest way in this case would be 通常不建议使用两个不同的Y比例尺创建图,但是在这种情况下,最简单的方法是
x <- rnorm(1000, sd=10)
xlim=c(-50, 40)
par(mar = c(5,4,4,5))
plot(density(x), xlim=xlim)
par(new=TRUE)
plot(ecdf(x), axes=F, xlab="", ylab="", main="", xlim=xlim)
axis(4)
mtext("ECDF",4, 3)
If you have a comelling reason not to want to set identical xlim values, you can borrow the answer from this question to extract the xlim from the previous plot 如果您有一个令人信服的理由不想设置相同的xlim值,则可以从该问题中借用答案以从上一个图中提取xlim
getplotlim<-function() {
usr <- par('usr')
xr <- (usr[2] - usr[1]) / 27 # 27 = (100 + 2*4) / 4
yr <- (usr[4] - usr[3]) / 27
list(
xlim = c(usr[1] + xr, usr[2] - xr),
ylim = c(usr[3] + yr, usr[4] - yr)
)
}
x <- rnorm(1000, sd=10)
par(mar = c(5,4,4,5))
plot(density(x))
par(new=TRUE)
plot(ecdf(x), axes=F, xlab="", ylab="", main="", xlim=getplotlim()$xlim)
axis(4)
mtext("ECDF",4, 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.