What is the Matplotlib.pyplot.stem() method in Python?
Overview
Matplotlib is used to visualize statistical data for clear and concise understanding. It makes complicated data coherent with the aid of different graphs and plots.
Stem plot
A graph is used to classify data as leaf and step. It has a baseline with heads moving outwards away from the baseline.
The Matplotlib.pyplot.stem() method
The stem() method of the matplotlib.pyplot API is used to create a stem plot. It can be plotted in two ways either vertically or horizontally.
Horizontal stem plot
For the horizontal stem plot, locs are x positions while the heads are y values.
Vertical stem plot
For the vertical stem plot, locs are y positions while the heads are x values.
Syntax
matplotlib.pyplot.stem(locs, heads, linefmt=None, markerfmt=None, basefmt=None)
Parameters
locs: For the horizontal plot, these are y-positions of the stem. On the other hand, for a vertical plot, these value shows the x-position of the stem.heads: For the horizontal plot, these are x-values of stem heads. On the other hand, for a vertical plot, these value shows the y-values of stem heads.linefmt: This string value defines the color and style of vertical lines.marketfmt: This string value defines the color and style of markers.basefmt: This is a format for the baseline.
Return value
This method returns a tuple of marker lines, stemlines, and baselines.
Example
# import libraries in programimport matplotlib.pyplot as pltimport numpy as np# generate x valuesx = np.linspace(1, 2** np.pi)# generate y values.y = np.exp(np.cos(x))# invoking stem() methodplt.stem(x, y, linefmt ='red', markerfmt ='-.', bottom = 1.1, use_line_collection = True)# save above generated plot as png image in root directoryplt.savefig('output/graph.png')
Explanation
- Lines 2 and 3: We import the
matplotlib.pyplotAPI aspltand NumPy asnp. - Line 5: We use the
np.linspace()method that generates 50 sample ranges between1and8.824977827076287. - Line 7: We calculate the exponent of
np.cos(x)values and return a list of 50 samples,x. - Line 9: We pass the following parameters to the
stemmethod: locsandheadsas a list of 50 values.linefmtindicates lines will beredin color.markerfmtshows the style of the marker.use_line_collectionis set toTrue, which means it will first use lines collection and then individual lines- Line 11: We use the
plt.savefig()method to save the output graph as agraph.pngfile.