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
stem() function in matplotlibMatplotlib has a built-in stem() function to create stem plots.
The stem() function can be implemented using the following syntax:
stem([x], y, linefmt=None, markerfmt=None, basefmt=None, bottom=0, label=None)
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.
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)
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
Line 8: A stem plot is created using the stem() function.
Line 9: The plot is saved in the output directory.
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)
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