Skip to course content
Free data visualization course

Data Visualization and Dashboard Storytelling

Unit 09.01: Controlling the axis rather than accepting it

Matplotlib chooses axis limits to fill the space, which for bars means a truncated axis by default.

The default is a decision you did not make

Three similar values plotted as bars, with the automatic limits reported and then set explicitly.

The code shows both.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

values = [102, 108, 96]
fig, ax = plt.subplots()
ax.bar(["A", "B", "C"], values)
auto_low, auto_high = ax.get_ylim()
print(f"axis chosen automatically: {auto_low:.1f} to {auto_high:.1f}")

ax.set_ylim(0, max(values) * 1.1)
low, high = ax.get_ylim()
print(f"axis set explicitly      : {low:.1f} to {high:.1f}")
print(f"\nautomatic baseline was {'zero' if auto_low == 0 else 'NOT zero'}")
plt.close(fig)

print("""
Matplotlib picks limits to fill the space, which for bars with similar values
means a truncated axis by default. For bars that is a misleading chart
produced by accepting a default.

Set the limits deliberately every time, and for bars set the floor to zero.
""")

The automatic baseline is not zero. That is a reasonable default for a line chart and a misleading chart for bars, produced by accepting a setting rather than choosing one.

Module 3 explained why bars must start at zero. This is the mechanical consequence: on a bar chart the floor has to be set on every figure, because the library will not do it for you.

The mistake this prevents

The mistake is checking the axis only when the chart looks wrong. It usually will not look wrong - a truncated bar chart looks like a chart with a large difference in it, which is exactly the problem.

Takeaway

Set axis limits explicitly on every figure, and set the floor to zero for bars. The automatic choice is optimised for filling space, not for honest encoding.