MATPLOTLIB:Bar charts, histograms, and box plots

Mastering bar charts, histograms, and box plots concepts and implementation.

Three questions, three charts

  • Bar: how much does each category have? One number per label.
  • Histogram: how are the numeric values spread? The chart builds the bins.
  • Box plot: where is the median, and where are the tails, for one or more groups?

Bars

import matplotlib.pyplot as plt
import pandas as pd

penguins = pd.read_csv("penguins.csv")
counts = penguins["species"].value_counts().sort_index()

fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(counts.index, counts.values, color="#7c3aed")
ax.set_ylabel("Birds")
ax.set_title("Penguins by species")
fig.tight_layout()

Sort the index when the category order should be stable from run to run. value_counts() alone sorts by count, which reshuffles the labels whenever the data changes.

ax.barh draws horizontal bars. Use it when the category names are long.

Histograms

import matplotlib.pyplot as plt
import pandas as pd

iris = pd.read_csv("iris.csv")

fig, ax = plt.subplots(figsize=(6, 4))
ax.hist(iris["sepal_length"], bins=12, color="#0f766e", edgecolor="white")
ax.set_xlabel("Sepal length (cm)")
ax.set_ylabel("Flowers")
ax.set_title("Iris sepal length")
fig.tight_layout()

bins is the number of intervals. Too few and the shape disappears. Too many and you are looking at noise. Twelve is a reasonable start for 150 iris rows.

Box plots

import matplotlib.pyplot as plt
import pandas as pd

penguins = pd.read_csv("penguins.csv")
groups = [
    penguins.loc[penguins["species"] == name, "body_mass_g"].dropna()
    for name in ["Adelie", "Chinstrap", "Gentoo"]
]

fig, ax = plt.subplots(figsize=(6, 4))
ax.boxplot(groups, labels=["Adelie", "Chinstrap", "Gentoo"])
ax.set_ylabel("Body mass (g)")
ax.set_title("Mass by species")
fig.tight_layout()

The line inside the box is the median. The box runs from the first quartile to the third. Points beyond the whiskers are the values Matplotlib flags as far from the rest. Gentoo's box sits higher than the other two, which matches the group means from the Pandas chapter.

What to notice

  • A bar chart of a mean is not a histogram. If the horizontal axis is species, it is a bar. If it is "grams, in bins", it is a histogram.
  • Pass a list of Series to boxplot when each group should be its own box. One Series makes one box.
  • edgecolor="white" on a histogram separates bins that would otherwise blend together.

Try this

Draw a histogram of petal_length from iris.csv with 15 bins, and a bar chart of how many flowers of each species are in that file.

Next: titles, legends, and files that still look right when you paste them into a document.