How to Create Stem Plot in Matplotlib: Simple Guide
To create a stem plot in
matplotlib, use the stem() function by passing your x and y data arrays. This function draws vertical lines from a baseline to the data points, showing discrete data clearly.Syntax
The basic syntax for a stem plot in Matplotlib is:
plt.stem(x, y, linefmt=None, markerfmt=None, basefmt=None)
where:
xis the sequence of x-coordinates.yis the sequence of y-coordinates (data values).linefmt(optional) sets the line style and color.markerfmt(optional) sets the marker style and color.basefmt(optional) sets the baseline style.
python
import matplotlib.pyplot as plt # Basic syntax plt.stem(x, y) plt.show()
Example
This example shows how to create a simple stem plot with x values from 0 to 9 and y values as their squares. It demonstrates the default stem plot style.
python
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) y = x ** 2 plt.stem(x, y) plt.title('Stem Plot Example') plt.xlabel('X values') plt.ylabel('Y = X squared') plt.show()
Output
A plot window showing vertical lines from x-axis to points (x, y) with markers at the top, titled 'Stem Plot Example'.
Common Pitfalls
Common mistakes when creating stem plots include:
- Not importing
matplotlib.pyplotornumpybefore plotting. - Passing mismatched lengths of
xandyarrays, causing errors. - Forgetting to call
plt.show()to display the plot. - Using outdated or incorrect format strings for line and marker styles.
python
import matplotlib.pyplot as plt import numpy as np # Wrong: x and y lengths differ x = np.arange(5) y = np.array([1, 4, 9]) # This will raise a ValueError # plt.stem(x, y) # Uncommenting causes error # Correct: x = np.arange(3) y = np.array([1, 4, 9]) plt.stem(x, y) plt.show()
Output
A stem plot with points at (0,1), (1,4), (2,9) displayed correctly.
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| x | Sequence of x-coordinates | [0, 1, 2, 3] |
| y | Sequence of y-coordinates | [1, 4, 9, 16] |
| linefmt | Line style and color | 'r-' (red solid line) |
| markerfmt | Marker style and color | 'bo' (blue circles) |
| basefmt | Baseline style | 'k-' (black solid line) |
Key Takeaways
Use plt.stem(x, y) to create a stem plot with your data points.
Ensure x and y arrays have the same length to avoid errors.
Call plt.show() to display the plot window.
Customize line and marker styles with optional format strings.
Stem plots are great for visualizing discrete data points clearly.