How to create a stem plot using matplotlib

Stem plots plot vertical lines at each x-axis location from the baseline to the y-axis, and place a marker there. They are similar to scatter plotsScatter plot is a diagram where each value in the data set is represented by a dot. because there are no links between individual data points.

The stem() function in matplotlib

Matplotlib has a built-in stem() function to create stem plots.

Syntax

The stem() function can be implemented using the following syntax:

stem([x], y, linefmt=None, markerfmt=None, basefmt=None, bottom=0, label=None)

Parameters

The following parameters are commonly used to implement the stem() function:

  • x: The is the position of the stems on the x-axis.

  • y: The is the position of the stem heads on the y-axis.

  • linefmt: This is a string defining the properties of the vertical lines.

  • markerfmt: This is a string defining the properties of the stem head markers.

  • basefmt: This is a string defining the properties of the baseline.

  • bottom: This is the position of the baseline on the y-axis.

  • label: The is the label to use for the stems in legends.

Note: The stem() function returns a StemContainer which may be considered like a tuple.

Create a basic stem plot

The following code returns a stem plot of cos(θ)cos(θ):

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.1, 2 * np.pi, 31)
y = np.exp(np.cos(x))
fig, axe = plt.subplots(dpi=800)
axe.stem(x, y)
fig.savefig("output/stem_plot.png")
plt.close(fig)

Code explanation

  • Line 4–5: We create x and y data points using numpy.

  • Line 7: We return a tuple (fig, axe) by using the subplots function of matplotlib with dpi distance per inchof 800.

  • Line 8: A stem plot is created using the stem() function.

  • Line 9: The plot is saved in the output directory.

Change the style of the stem plot

The linefmt , markerfmt and basefmt parameters in the stem() function are usually used to change the style of the plot. The following example illustrates how the style of a stem plot is changed:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.1, 2 * np.pi, 31)
y = np.exp(np.cos(x))
fig, axe = plt.subplots(dpi=400)
axe.stem(x, y, linefmt='r:', markerfmt='*b', basefmt='-g', bottom=1.0)
fig.savefig("output/stemplot_design.png")
plt.close(fig)

Code explanation

  • Line 8: We change the style of the stem plot in the stem() function.

    • The linefmt defines the color of the vertical line to be r(red) and makes it dotted using :.

    • The markerfmt defines the color of the marker to be b(blue) and the marker design to be *.

    • The baselinefmt defines the color of the baseline to be g(green) and the design to be -.

A stem plot is used to classify either discrete or continuous variables. The stem plot clearly shows the shape of a data set’s distribution.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved