user1424739
user1424739

Reputation: 13675

How to auto adjust the ylim of multi-histogram in basic R?

hist(sqrt(runif(100))
    , border = 'red'
    , breaks = seq(from=0, to=1, length.out=21)
    , col = 'red'
    , angle = 45, density=10, xlim=c(0, 1)
  )

hist(1-sqrt(runif(1000))
    , border = 'blue'
    , breaks = seq(from=0, to=1, length.out=21)
    , col = 'blue'
    , angle = 135, density=10, add=T
  )

The code like above can not recognize that the ylim of the first plot is too small. Is there a way in basic R to determine the appropriate ylim beforehand so that the first plot can be plotted with the correct ylim?

enter image description here

Upvotes: 0

Views: 312

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173803

You can precalculate the maximum y height of the second histogram. Suppose you have the data for the second histogram:

b_data <- 1 - sqrt(runif(1000))

Then you call hist on this data but without plotting it (hist silently returns a list-like object of breaks, counts, density etc, but you can specify plot = FALSE to get this object without drawing anything).

b <- hist(b_data, breaks = seq(from=0, to=1, length.out=21), plot = FALSE)

Now your code is essentially as before except you set the ylim of your first histogram to the maximum count of the second histogram:

hist(sqrt(runif(100))
    , border = 'red'
    , breaks = seq(from=0, to=1, length.out=21)
    , col = 'red'
    , angle = 45, density=10, xlim=c(0, 1), ylim = c(0, max(b$counts))
  )

hist(b_data, 
    , border = 'blue'
    , breaks = seq(from=0, to=1, length.out=21)
    , col = 'blue'
    , angle = 135, density=10, add=T
  )

enter image description here

Upvotes: 2

Related Questions