Step Function Plots with stairs(values)ΒΆ
The stairs() method draws a stepwise constant function β a horizontal line at each value that jumps vertically to the next value at each boundary. Unlike plot() which connects points with diagonal lines, stairs() maintains constant values between transitions, accurately representing discrete or binned data.
Why this matters for data science: Step functions are the correct way to visualize histogram bin values, cumulative distribution functions (CDFs), piecewise constant models like decision tree predictions, and any data where values change abruptly rather than continuously. Using a smooth line plot for such data would be misleading, as it implies gradual transitions that do not exist. The stairs() method is the modern replacement for the older step() function, and it works naturally with histogram output β you can pass np.histogram() results directly. The linewidth=2.5 parameter makes the steps more prominent. Note that stairs() takes one fewer boundary than step() expects, since it implicitly defines the intervals between consecutive boundaries.
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('_mpl-gallery')
# make data
y = [4.8, 5.5, 3.5, 4.6, 6.5, 6.6, 2.6, 3.0]
# plot
fig, ax = plt.subplots()
ax.stairs(y, linewidth=2.5)
ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
ylim=(0, 8), yticks=np.arange(1, 8))
plt.show()