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()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
MediumAn 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.
- Draw a histogram of
weightswith that many bins, keeping whatax.histreturns. - 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 applesAnd the chart looks like this:
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()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler