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
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 aStemContainerwhich may be considered like a tuple.
Create a basic stem plot
The following code returns a stem plot of
import matplotlib.pyplot as pltimport numpy as npx = 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
xandydata points usingnumpy.Line 7: We return a tuple (
fig, axe) by using thesubplotsfunction of matplotlib with of 800.dpi distance per inch Line 8: A stem plot is created using the
stem()function.Line 9: The plot is saved in the
outputdirectory.
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 pltimport numpy as npx = 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
linefmtdefines the color of the vertical line to ber(red) and makes it dotted using:.The
markerfmtdefines the color of the marker to beb(blue) and the marker design to be*.The
baselinefmtdefines the color of the baseline to beg(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