Menu
CoddyTech

Density Histograms

Part of the Statistics for ML section of Coddy's Machine Learning journey. Lesson 7 of 64.

This chapter is about the shape of data. By its end, you will fit a bell curve to a histogram and spot the odd one out:

A histogram of 300 melon weights with a smooth orange bell curve over it and a red dot under the lightest melon

First, a fix. Counts let a big group dwarf a small one, like 500 adults' reaction times against 50 gamers':

Two charts of the same reaction times. Left, counts: 500 adults tower over 50 gamers, whose bars barely show. Right, density=True: both groups show in full, the gamers faster and more bunched

density=True scales each group so its bar areas add up to 1:

ax.hist(adults, bins=16, density=True, alpha=0.5, label="adults")
ax.hist(gamers, bins=16, density=True, alpha=0.5, label="gamers")

Each height is count / (n * bin width), so a bar's area is its share of the group. Groups of any size now compare fairly.

challenge icon

Challenge

Easy

A city hospital weighed 400 newborns, a rural one 60. The starter holds the weights in city and rural and sets up the titled, labelled chart.

  1. Draw a density histogram of each group with bins=10, alpha=0.5 and the label city or rural.
  2. Add a legend and show the chart.

Coddy describes your chart. It should look like this one, from two tomato growers:

Two see-through density histograms titled Tomato Weights: farm tomatoes from about 90 to 200 grams, garden tomatoes lighter, mostly 95 to 145, with a legend

Try it yourself

import numpy as np
import matplotlib.pyplot as plt

# Don't change the lines below
rng = np.random.default_rng(23)
city = np.round(rng.normal(3.4, 0.5, size=400), 2)
rural = np.round(rng.normal(3.2, 0.45, size=60), 2)

fig, ax = plt.subplots()
ax.set_title("Birth Weights")
ax.set_xlabel("Weight (kg)")
ax.set_ylabel("Density")

# Write your code below
quiz iconTest yourself

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

All lessons in Statistics for ML

Practice on your own: Online Python compiler