将ecdf和密度绘制到具有不同y轴的相同图形中

时间:2021-11-04 12:49:04

Consider the two following plots:

请考虑以下两个图:

x <- rnorm(1000, sd=10)
plot(density(x))
plot(ecdf(x))

Please note the different y-axis ranges:

请注意不同的y轴范围:

将ecdf和密度绘制到具有不同y轴的相同图形中将ecdf和密度绘制到具有不同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?

1 个解决方案

#1


1  

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)

将ecdf和密度绘制到具有不同y轴的相同图形中

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)

#1


1  

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)

将ecdf和密度绘制到具有不同y轴的相同图形中

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)