Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206235

Common breaks and free axes for overlapping lattice histograms

$
0
0

What is the required incantation to achieve an overlapping, faceted lattice::histogram with common break points (across groups, but potentially varying across panels)?

For example, assume I want the total range of the data (groups combined) for each panel to be split into 30 bins.

Example data:

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)

Using nint=30?

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

enter image description here

Above, the bins are consistent across groups, but (1) the x-axis limits are shared across panels (problematic when the x-axis range varies substantially across panels - I really want the 30 bins to be calculated individually for each panel), and (2) the y-axis is cramped when using type='percent' (it should extend further).

Using breaks=30?

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

enter image description here

Now the axis limits look good, but the bins width varies across groups.

So...

Using lattice, how can I achieve overlapping, faceted histograms that have constant bin width across groups within panels, but have axis limits that fit the data for each panel?

(I realise that ggplot is an option, but I want the figure style to be consistent with my other lattice plots.)


Viewing all articles
Browse latest Browse all 206235

Trending Articles