Skip to content

Instantly share code, notes, and snippets.

@johnbaums
Created January 22, 2020 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnbaums/028106a8b82dc27937ec9bb6de01da8e to your computer and use it in GitHub Desktop.
Save johnbaums/028106a8b82dc27937ec9bb6de01da8e to your computer and use it in GitHub Desktop.
Fix axis limits for overlapping lattice histograms
# See https://stackoverflow.com/q/59851541/489704
fix_limits <- function(p) {
if(!is.numeric(p$panel.args.common$breaks))
stop('trellis object should be constructed specifying nint')
b <- p$panel.args.common$breaks
pad <- diff(b[1:2])
lims <- lapply(p$panel.args, function(x) {
bins <- findInterval(x$x, b)
ymax <- max(unlist(tapply(bins, p$panel.args.common$groups[x$subscripts],
function(y) table(y)/length(y)))) + 0.025
ylims <- c(0, 100*ymax)
xlims <- b[range(bins)] + c(-3*pad, 4*pad)
list(xlims=xlims, ylims=ylims)
})
p$x.limits <- lapply(lims, '[[', 'xlims')
p$y.limits <- lapply(lims, '[[', 'ylims')
p
}
@johnbaums
Copy link
Author

Example from https://stackoverflow.com/q/59851541/489704

library(lattice)
set.seed(1)
d <- data.frame(v1=rep(c('A', 'B'), each=1000), 
                v2=rep(c(0.5, 1), each=2000),
                mean=rep(c(0, 10, 2, 12), each=1000))
d$x <- rnorm(nrow(d), d$mean, d$v2)

p1 <- histogram(~x|v1, d, groups=v2, nint=100,
                scales=list(relation='free'), type='percent',
                panel = function(...) {
                  panel.superpose(..., panel.groups=panel.histogram, 
                                  col=c('red', 'blue'), alpha=0.3)
                })
p1

image

fix_limits(p1)

image

@johnbaums
Copy link
Author

johnbaums commented Jan 22, 2020

But this doesn't work well when panels have wildly different ranges - the bins are calculated along the combined x-axis. Above, I would want the x-axis of each panel to be split into 100 bins.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment