TExcelTAD
Home › Matplotlib › Step & Stem Plots

Step & Stem Plots

A normal line plot implies that values change smoothly between points. That is wrong for many datasets: a price that stays fixed until the next change, a count of items in stock, or separate samples of a signal. Step plots and stem plots show such data honestly.

Step plots

ax.step(x, y) draws horizontal segments with vertical jumps. The where argument decides where the jump happens:

where= The value at x[i] holds …
"pre" (default) on the interval before x[i] (jump at x[i-1])
"post" from x[i] until the next point
"mid" jump halfway between points
python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 6)
y = np.array([2, 4, 3, 5, 1, 3])

fig, ax = plt.subplots()
for offset, where in enumerate(["pre", "mid", "post"]):
    ax.step(x, y + offset * 6, where=where, label=f'where="{where}"')
    ax.plot(x, y + offset * 6, "o", color="0.4", ms=4)
ax.legend(loc="upper left", ncols=3)
ax.set_ylim(0, 22)
plt.show()

print("Same data drawn 3 times; points:", x.size)
Same data drawn 3 times; points: 6

For a price list ("this price is valid from this date on") where="post" is the right choice:

python · try it yourself
import matplotlib.pyplot as plt

change_day = [0, 14, 30, 45, 61, 90]
price = [4.20, 4.50, 4.50, 4.80, 4.60, 4.60]   # last value repeats so the step reaches day 90

fig, ax = plt.subplots(figsize=(7, 3.5), layout="constrained")
ax.step(change_day, price, where="post", color="C2", lw=2)
ax.set(xlabel="Day", ylabel="Price (€)", title="Coffee price changes", ylim=(4, 5))
plt.show()

def price_on(day):
    current = price[0]
    for d, p in zip(change_day, price):
        if d <= day:
            current = p
    return current

print("Price on day 50:", price_on(50))
Price on day 50: 4.8

Tip: ax.plot(x, y, drawstyle="steps-post") gives the same result as step(..., where="post"), and ax.stairs(values, edges) draws steps from bin edges, which suits pre-computed histograms.

Stem plots

A stem plot draws a vertical line from a baseline to each value, topped by a marker. It is used for discrete samples, for example a digital signal or the coefficients of a model:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

n = np.arange(0, 20)
signal = np.cos(2 * np.pi * n / 10) * np.exp(-n / 12)

fig, ax = plt.subplots(figsize=(7, 3.5), layout="constrained")
markers, stems, baseline = ax.stem(n, signal)
ax.set(xlabel="Sample n", ylabel="Amplitude", title="A sampled, decaying cosine")
plt.show()

print("Samples:", n.size)
print("First 4 values:", np.round(signal[:4], 3).tolist())
Samples: 20
First 4 values: [1.0, 0.744, 0.262, -0.241]

stem() returns three objects that can be styled afterwards with plt.setp:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

features = ["age", "income", "visits", "tenure", "discount", "region"]
weight = np.array([0.42, 0.18, 0.75, -0.30, -0.12, 0.05])

fig, ax = plt.subplots()
markers, stems, baseline = ax.stem(features, weight, basefmt="k-")
plt.setp(markers, color="C3", markersize=8)
plt.setp(stems, color="C3", linewidth=2)
ax.set(ylabel="Coefficient", title="Model coefficients")
plt.show()

strongest = features[int(np.abs(weight).argmax())]
print("Strongest effect:", strongest, weight[np.abs(weight).argmax()])
Strongest effect: visits 0.75

Positive and negative coefficients stand out clearly against the baseline at 0 (basefmt="k-" draws it as a solid black line).

Horizontal stems

orientation="horizontal" turns the stems sideways, which works like a "lollipop" chart for ranked categories:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

teams = ["Atlas", "Borealis", "Comet", "Delta", "Echo"]
tickets = np.array([34, 58, 21, 47, 66])
order = tickets.argsort()

fig, ax = plt.subplots()
ax.stem(np.arange(len(teams)), tickets[order], orientation="horizontal")
ax.set_yticks(range(len(teams)), [teams[i] for i in order])
ax.set(xlabel="Tickets closed", xlim=(0, 75))
plt.show()

print("Ranking:", [teams[i] for i in order[::-1]])
Ranking: ['Echo', 'Borealis', 'Delta', 'Atlas', 'Comet']

Test yourself

A value is valid from its x position until the next point. Which step setting matches?

  1. where="pre"
  2. where="mid"
  3. where="post"
  4. where="next"

What does a stem plot draw for each data point?

  1. A bar of fixed width
  2. A line from the baseline to the value, with a marker on top
  3. A box with whiskers
  4. A pie wedge

Which plot keyword gives a step-style line?

  1. linestyle="steps"
  2. drawstyle="steps-post"
  3. step=True
  4. marker="step"