0
0
MatplotlibHow-ToBeginner ยท 3 min read

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:

  • x is the sequence of x-coordinates.
  • y is 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.pyplot or numpy before plotting.
  • Passing mismatched lengths of x and y arrays, 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

ParameterDescriptionExample
xSequence of x-coordinates[0, 1, 2, 3]
ySequence of y-coordinates[1, 4, 9, 16]
linefmtLine style and color'r-' (red solid line)
markerfmtMarker style and color'bo' (blue circles)
basefmtBaseline 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.