CodeBlanks Logo Icon CodeBlanks

Histogram

A histogram shows data distribution with bars.

Histogram

A histogram shows the distribution of a single variable: the value range is split into bins (bins) and the number of examples in each bin is drawn as a bar. Skew, multiple peaks and outliers show up here.

fig, ax = plt.subplots()
ax.hist(x, bins=20, edgecolor="black")
sayi, sinir = np.histogram(x, bins=20)   # same counts, no drawing

np.histogram gives the same bin counts and edges without drawing.

Bin count and comparison

Few bins hide detail, many bins produce noise. To compare classes, histograms are drawn semi-transparent on the same axis:

for k in [0, 1]:
    ax.hist(X[y == k, 0], bins=20, alpha=0.5, label=f"sınıf {k}")
ax.legend()

If the two classes' histograms overlap a lot, that feature is weak at separating the classes.

Practice Count the distribution

Draw a 4-bin histogram of x and save it. Get the same counts with np.histogram(x, bins=4); print the counts and the edges on separate lines.

Starter code

model.py
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 2, 3, 3, 3, 4, 4, 5, 9])

# buraya yaz

Sample solution

model.py
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 2, 3, 3, 3, 4, 4, 5, 9])

fig, ax = plt.subplots()
ax.hist(x, bins=4)
fig.savefig("hist.png")
sayi, sinir = np.histogram(x, bins=4)
print(sayi)
print(sinir)

Expected output

[3 5 1 1]
[1. 3. 5. 7. 9.]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many bin edges does <code>np.histogram(x, bins=10)</code> return?

  • 9
  • 20
  • 11 Correct answer
  • 10

Explanation: The starts and ends of 10 bins: 11 edges; the count array has 10 elements.

2 Show the legend.

Question
ax.____()
Answer
ax.legend()

Explanation: legend draws the key for plots that were given a label.

3 Match the concepts.

Term Meaning
bins Number of bins
np.histogram Counting without drawing
label Legend text
overlapping histogram Weak separating feature

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation