0

Consider the two following plots:

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

Please note the different y-axis ranges:

density ecdf

Now I would like to have these two in one graph and two y-axis.

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.

Is there an easy way of getting these two into one graph, left y-axis density, right y-axis ecdf?

Rainer
  • 8,347
  • 1
  • 23
  • 28
  • With ggplot, have you considered http://stackoverflow.com/questions/26727741/how-to-show-a-legend-on-dual-y-axis-ggplot – lawyeR May 22 '15 at 12:30

1 Answers1

1

Create plots with two different Y scales is not generally recommended, but the easiest way in this case would be

    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)

enter image description here

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

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)
Community
  • 1
  • 1
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • I wanted to avoid to set =xlim, as I have to make the function which is plotting the two graphs more complex. But I must say I really love your second suggestion and I will use it quite often. – Rainer May 26 '15 at 11:17