Menu
CoddyTech

Histograms

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 27 of 60.

Twelve help desk calls, in minutes. A histogram shows how numbers like these spread: it cuts their range into equal bins and counts the values in each:

calls = [2, 3, 3, 4, 5, 5, 6, 6, 6, 7, 9, 14]
fig, ax = plt.subplots()
counts, edges, bars = ax.hist(calls, bins=4)
print(counts)
print(edges)
plt.show()

A histogram of 12 call lengths in 4 bins with edges 2, 5, 8, 11 and 14: bars of 4, 6, 1 and 1 calls

Most calls take 2 to 8 minutes. ax.hist also returns what it counted, so this prints:

[4. 6. 1. 1.]
[ 2.  5.  8. 11. 14.]

4 bins need 5 edges. A value sitting on an edge goes to the bin on its right, except the largest, which stays in the last bin.

challenge icon

Challenge

Medium

An orchard weighed 120 apples into weights (grams). The program reads a number of bins; the starter sets up the titled, labelled chart and shows it.

  1. Draw a histogram of weights with that many bins, keeping what ax.hist returns.
  2. Print the fullest bin's edges, rounded to 1 decimal, and its count, as below.

For another orchard and 6 bins, the program prints this line, then Coddy describes the chart:

Fullest bin: 153.6 to 167.8 g, 38 apples

And the chart looks like this:

A histogram titled Apple Weights with 6 bars from about 125 to 210 grams, the tallest, 38 apples, between 154 and 168 grams

Try it yourself

import numpy as np
import matplotlib.pyplot as plt

bins = int(input())

# Don't change the lines below
rng = np.random.default_rng(11)
weights = rng.normal(150, 20, size=120)
fig, ax = plt.subplots()
ax.set_title("Apple Weights")
ax.set_xlabel("Weight (g)")
ax.set_ylabel("Apples")

# Write your code below

# Don't change the line below
plt.show()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler