Align axis ticks with bins in a lattice histogram

1.6k views Asked by At

I plotted a histogram using Lattice

histogram(~Time |factor(Bila), data=flexi2, xlim= c(5, 15), ylim=c(0, 57),
      scales=list(x=list(at=seq(5,15,1))), xlab="Time", 
      subset=(Bila%in% c("")))`

The bins I get do not match the exact hours, whereas I would like the bin to start at the exact hour, for example, 6,7 etc. I use lattice since I want conditional histograms. I have extracted here just one histogram to illustrate. enter image description here

UPDATE: Here is a reproducible example (I hope) as was requested. As can be seen 0 for example is not at the limit of bins.

x<-rnorm(1000)
histogram(~x)

enter image description here

1

There are 1 answers

0
shadowtalker On BEST ANSWER

This happens because you specified the x axis scale with scales = list(x = list(at = 5:15)), but you didn't actually change the breakpoints. It happens in the default case as well: the default axis labels are integers, but the default breakpoints are determined programmatically and are not necessarily integers unless you have integer-valued data.

An easy fix would be to specify your own breaks in the breaks argument:

histogram(~Time |factor(Bila), data=flexi2, subset=(Bila %in% c("")),
  xlim= c(5, 15), ylim=c(0, 57),
  breaks = 5:15,
  scales = list(x = list(at = 5:15)),
  xlab="Time")

And an example:

library(lattice)
x <- rnorm(1000)
x[abs(x) > 3] <- 3
x_breaks <- c(-3, -1.5, 0, 1.5, 3)
histogram(~ x,
          title = "Defaults")
histogram(~ x, breaks = x_breaks,
          title = "Custom bins, default tickmarks")
histogram(~ x, scales = list(x = list(at = x_breaks)),
          title = "Custom tickmarks, default bins")
histogram(~ x, breaks = x_breaks, scales = list(x = list(at = x_breaks)),
          title = "Custom tickmarks, custom bins")