How to Create Step Plot in Matplotlib: Simple Guide
To create a step plot in
matplotlib, use the plt.step() function, which draws lines that change values in steps instead of straight lines. You provide your x and y data arrays, and optionally set the where parameter to control step positioning.Syntax
The basic syntax for a step plot in Matplotlib is:
plt.step(x, y, where='pre')
Here:
xis the sequence of x-coordinates.yis the sequence of y-coordinates.wherecontrols the step position and can be'pre','post', or'mid'.
python
import matplotlib.pyplot as plt plt.step(x, y, where='pre') plt.show()
Example
This example shows how to create a simple step plot with three different step positions: 'pre', 'post', and 'mid'.
python
import matplotlib.pyplot as plt import numpy as np x = np.arange(5) y = np.array([1, 3, 2, 5, 4]) plt.figure(figsize=(8, 4)) plt.step(x, y, where='pre', label='where="pre"') plt.step(x, y, where='post', label='where="post"') plt.step(x, y, where='mid', label='where="mid"') plt.legend() plt.title('Step Plot Example') plt.xlabel('X axis') plt.ylabel('Y axis') plt.grid(True) plt.show()
Output
A plot window showing three step plots with different step positions labeled 'where="pre"', 'where="post"', and 'where="mid"'. The lines look like stairs with steps aligned differently relative to the x values.
Common Pitfalls
Common mistakes when creating step plots include:
- Not setting the
whereparameter, which defaults to'pre'and may not match your expected step alignment. - Using non-monotonic or unsorted
xvalues, which can cause confusing plots. - Passing mismatched lengths of
xandyarrays, which raises errors.
Always ensure your data is sorted and where is set as needed.
python
import matplotlib.pyplot as plt # Wrong: mismatched lengths x = [0, 1, 2] y = [1, 2] # plt.step(x, y) # This will raise a ValueError # Correct: x = [0, 1, 2] y = [1, 2, 3] plt.step(x, y, where='post') plt.show()
Output
A step plot with steps aligned after each x value, showing a correct plot without errors.
Quick Reference
Summary tips for step plots in Matplotlib:
- Use
plt.step(x, y, where='pre')for steps starting at the x value. - Use
where='post'for steps ending at the x value. - Use
where='mid'for steps centered between x values. - Ensure
xandyhave the same length andxis sorted. - Use
plt.grid(True)to improve plot readability.
Key Takeaways
Use plt.step(x, y, where='pre'|'post'|'mid') to create step plots with different step alignments.
Ensure your x and y data arrays are the same length and x is sorted for correct plotting.
The 'where' parameter controls if steps change before, after, or in the middle of x points.
Common errors come from mismatched data lengths or unsorted x values.
Adding plt.grid(True) helps make step plots easier to read.