A Practical Summary of Matplotlib in 13 Python Snippets | by Lucas Soares | Towards Data Science

Matplotlib is the bread and butter of data visualization in Python. To get the most out of it, one needs to practice it’s multiple features and functionalities to be able to customize plots at will.
In this article, I will show you 13 scripts that summarize the basics of Matplotlib
[[Updated 2021]]
If you prefer you can check out my Youtube video on this topic:
import matplotlib.pyplot as pltimport numpy as npfig,axs = plt.subplots(figsize=(15,7)) data1 = np.random.normal(0,1,100)data2 = np.random.normal(0,1,100)data3 = np.random.normal(0,1,100)x_ax = np.arange(0,100,10)y_ax = np.arange(-3,3,1)axs.plot(data1,marker="o")axs.plot(data2,marker="*")axs.plot(data3,marker="^")axs.set_xticks(x_ax)axs.set_xticklabels(labels=x_ax,rotation=45)axs.set_yticks(y_ax)axs.set_yticklabels(labels=y_ax,rotation=45)axs.set_xlabel("X label")axs.set_ylabel("Y label")axs.set_title("Title")axs.grid("on")
As noted in the documentation, there are essentially two ways to use Matplotlib:
OO-style: create figures and axes explicitly, and call methods on them
Pyplot-style: rely on the pyplot module to automatically create and manage the figures and axes.
import matplotlib.pyplot as pltimport numpy as npx = np.cos(np.linspace(0, 2, 100)) # Create the data# Note that even in the OO-style, we use `.pyplot.figure` to create the figure.fig, ax = plt.subplots()  # Create a figure and an axes with pyplot.subplots()ax.plot(x, x, label='linear')  # Plot some data on the axes.ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...ax.plot(x, x**3, label='cubic')  # ... and some more.ax.set_xlabel('x label')  # Add an x-label to the axes.ax.set_ylabel('y label')  # Add a y-label to the axes.ax.set_title("Simple Plot")  # Add a title to the axes.ax.legend();  # Add a legend.
import matplotlib.pyplot as pltimport numpy as npx = np.cos(np.linspace(0, 2, 100)) # Create the dataplt.plot(x, x, label='linear')  # Plot some data on the (implicit) axes.plt.plot(x, x**2, label='quadratic')  # same pipeline but using pyplot.plot directlyplt.plot(x, x**3, label='cubic')plt.xlabel('x label')plt.ylabel('y label')plt.title("Simple Plot")plt.legend();
The examples from Matplotlib’s documentation use both approaches, but highlight that it is preferable to pick one of them and stick to it. The suggestion is to restrict pyplot to interactive plotting (e.g., in a Jupyter notebook), and to prefer the OO-style for non-interactive plotting.
# source: https://matplotlib.org/stable/tutorials/introductory/usage.html#sphx-glr-tutorials-introductory-usage-pyimport matplotlib.pyplot as pltimport numpy as npdef my_plotter(ax, data1, data2, param_dict):    """    A helper function to make a graph    Parameters    ----------    ax : Axes        The axes to draw to    data1 : array       The x data    data2 : array       The y data    param_dict : dict       Dictionary of kwargs to pass to ax.plot    Returns    -------    out : list        list of artists added    """    out = ax.plot(data1, data2, **param_dict)    return outdata1, data2, data3, data4 = np.random.randn(4, 100)fig, ax = plt.subplots(1, 1)my_plotter(ax, data1, data2, {'marker': 'x'})# 2 sub-plots examplefig, (ax1, ax2) = plt.subplots(1, 2)my_plotter(ax1, data1, data2, {'marker': 'x'})my_plotter(ax2, data3, data4, {'marker': 'o'});
import matplotlib.pyplot as pltimport numpy as npt = np.sin(np.linspace(-3,3,50))# red dashes, blue squares and green trianglesplt.plot(t, t, 'r--', color="red")plt.plot(t, t**2, 'bs', color="blue")plt.plot(t, t**3, 'g^', color="green")plt.plot(t, t**4, "o", color="orange")plt.plot(t, t**5, "o-", color="black")plt.show()
See more at
Customizing style sheets in matplotlib
pyplot.setp documentation
Controlling Line Properties
# source: https://matplotlib.org/stable/gallery/misc/keyword_plotting.htmlimport matplotlib.pyplot as pltimport numpy as npdata = {'a': np.arange(50),        'c': np.random.randint(0, 50, 50),        'd': np.random.randn(50)}data['b'] = data['a'] + 10 * np.random.randn(50)data['d'] = np.abs(data['d']) * 100plt.scatter('a', 'b', c='c', s='d', data=data)plt.xlabel('entry a')plt.ylabel('entry b')plt.show()
import matplotlib.pyplot as pltimport numpy as npnames = ['cats', 'dogs', 'dragons']values = [5, 25, 125]plt.figure(figsize=(15, 7))plt.subplot(131)plt.bar(names, values, color="red", label="bar chart")plt.legend()plt.subplot(132)plt.scatter(names, values, color="orange", label="scatter plot")plt.legend()plt.subplot(133)plt.plot(names, values, color="green", label="line plot")plt.legend()plt.suptitle('Categorical Plots')plt.show()
import matplotlib.pyplot as pltimport numpy as npdef f(t):    return np.exp(-t) * np.cos(2*np.pi*t)t1 = np.arange(0.0, 5.0, 0.1)t2 = np.arange(0.0, 5.0, 0.2)plt.figure()plt.subplot(2,2,1)plt.plot(t1, f(t1), 'black')plt.subplot(2,2,2)plt.plot(t2, np.tan(2*np.pi*t2), 'r--')plt.subplot(2,2,3)plt.plot(t2, np.exp(t2), 'g^')plt.subplot(2,2,4)plt.plot(t2, np.cos(2*np.pi*t2), 'orange');
You can use figure numbers to create multiple figures:
import matplotlib.pyplot as pltimport numpy as npplt.figure(1)plt.subplot(121)plt.plot([1, 2, 3])plt.subplot(122)plt.plot([4, 5, 6])plt.figure(2)plt.subplot(121)plt.plot([1, 2, 3],color="red")plt.subplot(122)plt.plot([4, 5, 6],color="red")plt.title('It is that simple');
See more on:
Working with multiple figures
Matplotlib allows you to easily write arbitrarily placed text inside plots using text objects.
#source: https://matplotlib.org/stable/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-pymu, sigma = 100, 15x = mu + sigma * np.random.randn(10000)# the histogram of the datan, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)plt.xlabel('Smarts')plt.ylabel('Probability')plt.title('Histogram of IQ')plt.text(60, .025, r'$\mu=100,\ \sigma=15$')plt.axis([40, 160, 0, 0.03])plt.grid(True)plt.show()
All of the text functions return a text object instance. Notice you can use math expressions in text, as done with the above example taken from Matplotlib’s documentation. The idea is to insert latex syntax in the text string:
plt.title(r'$\sigma_i=15$')Text(0.5, 1.0, '$\\sigma_i=15$')
More at:
Introduction to text in Matplotlib
Introduction to pyplot
# source: https://matplotlib.org/stable/tutorials/text/annotations.htmlax = plt.subplot()t = np.arange(0.0, 5.0, 0.01)s = np.cos(2*np.pi*t)line, = plt.plot(t, s, lw=2)plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),             arrowprops=dict(facecolor='black', shrink=0.05),             )plt.ylim(-2, 2)plt.show()
See more at:
Working with annotations
# adapted from: https://matplotlib.org/stable/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py# make up some data in the open interval (0, 1)y = np.random.normal(loc=0.5, scale=0.4, size=1000)y = y[(y > 0) & (y < 1)]y.sort()x = np.arange(len(y))# plot with various axes scalesplt.figure()# linearplt.subplot(221)plt.plot(x, y, color="red")plt.yscale('linear')plt.title('linear',color="red")plt.grid(True)# logplt.subplot(222)plt.plot(x, y, color="green")plt.yscale('log')plt.title('log',color="green")plt.grid(True)# symmetric logplt.subplot(223)plt.plot(x, y - y.mean(),color="blue")plt.yscale('symlog', linthresh=0.01)plt.title('symlog',color="blue")plt.grid(True)# logitplt.subplot(224)plt.plot(x, y, color="orange")plt.yscale('logit')plt.title('logit',color="orange")plt.grid(True)# Adjust the subplot layout, because the logit one may take more space# than usual, due to y-tick labels like "1 - 10^{-3}"plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,                    wspace=0.35)plt.tight_layout()plt.show()
See more at:
Introduction to pyplot
These are just a few examples of the universe of graphical possibilities behind Matplotlib. I encourage you to read the documentation further and study the proper practices to master Matplotlib. For those working with it on a daily basis, I guarantee it is a worthy pursuit!
Source code with the notebook for this article can be found here.
If you want to learn more about Python and data visualization, check out these courses from Udemy:
These are affiliate links, if you use them I get a small commission, cheers! :)
Python for Data Science A-Z
Learn Python for Data Visualization
Data Visualization in Python Masterclass
If you liked this post connect with me on Twitter, LinkedIn, Instagram, and follow me on Medium. Thanks and see you next time!
Matplotlib documentation
Customizing style sheets in matplotlib
pyplot.setp documentation
Controlling Line Properties
Working with multiple figures
Introduction to text in Matplotlib
Introduction to pyplot
Working with annotations