I'd like to center the bars in my histograms over the correct values of the x-axis.

Here is a simplified example:

simplified example

The most common value in the dataset is zero, but glancing at the histogram this isn't apparent. It might be zero, or it might be one. This histogram also makes one wonder if the number three appears in the dataset (and it doesn't).

Here's a photoshop mockup of what I'd like (for the same dataset input)

desired output

Kind thanks in advance for any help.


1 Answer 1

Histogram[{0, 0, 0, 1, 1, 2}, {1},  Ticks -> {{# + .5, #} & /@ Range[-1, 3], Automatic}]

enter image description here

Update 1: More generally, without hard-coding the range of values, you can use HistogramList as follows:

data = {0, 0, 0, 1, 1, 2};
bspec = {1};
Histogram[data, bspec, 
   Ticks -> {{# + .5, #} & /@ HistogramList[data, bspec][[1]],  Automatic}]
(* same picture *)

Update 2: You can also use a combination of HistogramList and BarChart:

hl = HistogramList[data, bspec];
BarChart[hl[[2]], ChartLabels -> Placed[hl[[1]], Below]]

enter image description here

  • $\begingroup$ Thanks, that's cute. Is is possible to do it without hard-coding the range of values? Ticks->Automatic works nicely when I happen to have a dataset that doesn't lie within [0,2]. (Some of my datasets are in [0,140000] for instance) $\endgroup$
    – Harold
    Commented Dec 21, 2014 at 21:38
  • 1
    $\begingroup$ @Harold, please see the update. $\endgroup$
    – kglr
    Commented Dec 21, 2014 at 21:42
  • $\begingroup$ Wow! Perfect. If only I could upvote you more than once. Warm regards. $\endgroup$
    – Harold
    Commented Dec 21, 2014 at 21:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.