Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 57 ยท Core Chart Types

Histograms and Distributions

Learn Matplotlib histograms: choosing bins, density, cumulative and stacked histograms, overlays, histtype, hist2d and hexbin, and bin-width pitfalls.

A histogram shows how a set of numbers is distributed. It cuts the number line into intervals called bins, counts how many values fall into each, and draws a bar per bin. Where a bar chart compares categories, a histogram describes one continuous variable: is it symmetric or skewed, one peak or two, tightly packed or spread out?

You will learn how bins work (and how to choose them), how to normalize, overlay and stack histograms, and how to extend the idea to two variables with hist2d and hexbin.

What a histogram answers

Shape Symmetric, skewed or lumpy?
Peaks One mode or several?
Spread Narrow or wide?
Outliers Values far from the rest.
1 / 2

Your first histogram

ax.hist(data, bins=...) counts and draws in one call. It also returns the counts, the bin edges and the bar objects, which is handy for checking what was drawn.

Python hist returns counts and edges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

There is always one more edge than there are bins, because the edges are the fence posts around the bars. The counts add up to 500, so every value was counted exactly once (the last bin includes its right edge, all others are half-open).

Choosing the bins

bins accepts several kinds of values:

  • an integer: that many equal-width bins between the minimum and maximum;
  • a sequence of edges: for complete control, including unequal widths (counts then mislead unless you use density=True);
  • a string rule such as "auto", "sturges", "fd" (Freedman-Diaconis) or "sqrt", which choose the number from the data.

You can ask NumPy what a rule would choose with np.histogram_bin_edges(data, bins="fd"). The result is the array of edges that hist would use.

Python Too few, too many, and rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With 3 bins the two groups merge into a single lump. With 80 bins the bars flicker because each holds only a few values. The middle chart shows two clear peaks. There is no universally correct bin count: start with a rule, then try half and double and see whether the story changes. If it does, be careful what you claim.

Counts, density and cumulative

By default each bar's height is a count. Two options change the vertical axis:

  • density=True scales the bars so the total area is 1. The heights are then probability densities, which let you compare data sets of different sizes or draw a theoretical curve on top.
  • cumulative=True makes each bar the number (or fraction) of values up to that bin, so the histogram becomes a staircase that rises to the total.
Python Density with a normal curve, and cumulative

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check the printed area: bar height times bar width, summed, equals 1. The heights themselves usually do not sum to 1, because each is divided by the bin width. With density=True, read the vertical axis as "per unit of x", not as a percentage.

Comparing several groups

To compare groups, you can overlay histograms or stack them.

  • Overlay: draw two hist calls with a low alpha, or use histtype="step" so only outlines show. Use density=True if the groups have different sizes, and give both the same bin edges; otherwise the bars disagree and the comparison is unfair.
  • Stack: pass a list of arrays and stacked=True to pile the groups into one bar per bin, showing the total and its composition.

histtype controls the look: "bar" (default), "barstacked", "step" (an unfilled outline) and "stepfilled".

Python Overlaying with shared bin edges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The groups have 400 and 250 values, so density=True is essential, otherwise the larger group would look like it has higher scores simply because its bars are taller.

Two variables: hist2d and hexbin

A histogram can also count pairs. ax.hist2d(x, y, bins=...) divides the plane into rectangles and colors each by its count; ax.hexbin(x, y, gridsize=...) does the same with hexagons, which avoid the visual grid bias of squares. Both rescue a scatter plot that has become an unreadable blob.

They return objects you pass to fig.colorbar, so the color scale is labelled.

Python hist2d and hexbin side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Choose a sequential colormap (see colormaps) because counts only go up from zero. For very large data sets this aggregation also keeps drawing fast, a theme you will meet again in Plotting Large Data Fast.

Bin-width pitfalls

  • Unequal bin widths with counts. A wide bin collects more values than a narrow one, so its bar is taller for no real reason. Use density=True, which divides by width.
  • Different edges per group. Overlays must share edges.
  • Edge placement. Shifting all edges by half a bin can move values into different bins and change the look. If the shape depends on the shift, it is not a robust feature.
  • Integer data. For whole numbers, use edges at half-integers (np.arange(0, 12) - 0.5) so each integer sits in the middle of its own bar instead of straddling two.
  • Hidden outliers. One extreme value stretches the range, squashes the bars into one corner. Set range=(low, high) or clip, and say that you did.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. ax.hist(data, bins=10) draws 10 bars. How many bin edges does it use?

    Edges are the fence posts around the bars, so n bins need n + 1 edges.
  2. 2. What does density=True do?

    Heights become density (count divided by total and by bin width), so the area under the bars is 1. It does not draw a curve.
  3. 3. You overlay histograms of two groups with different sizes. What two things keep the comparison fair?

    Sharing edges makes the bars comparable, and density removes the effect of group size.
  4. 4. Which tool is best when a scatter plot of 100,000 points is an unreadable blob?

    They aggregate points into counts per cell, so density is visible and drawing is fast.
  5. 5. Why use bin edges at half-integers for whole-number data?

    An integer on a bin boundary is counted in one neighbour and looks off-center. Half-integer edges center each value.

Summary

  • ax.hist(data, bins=...) counts and draws; it returns (counts, edges, patches).
  • bins can be an integer, explicit edges or a rule such as "fd"; always test several choices because bins shape the story.
  • density=True makes the area 1 (use it to compare unequal groups); cumulative=True shows running totals.
  • Overlay groups with shared edges, low alpha or histtype="step"; stack with stacked=True.
  • hist2d and hexbin count pairs of values and cure overplotting; add a colorbar.
  • Watch for unequal bin widths, different edges per group and extreme outliers.

Next, summarize distributions compactly in Box Plots and Violin Plots.