Master Matplotlib: From Simple Plots to Advanced Visualizations
This tutorial walks you through the essentials of Matplotlib, showing how to create basic figures, customize subplots, style lines and markers, adjust axes and legends, add annotations and patches, save figures in various formats, and tweak global settings for professional-quality visualizations.
Matplotlib Overview
Matplotlib is a versatile Python library for creating static, animated, and interactive visualizations. It originated in 2002 to provide MATLAB‑style plotting in Python and now supports a wide range of output formats (PDF, SVG, PNG, etc.).
1. Simple Plot and Figure Creation
In a Jupyter notebook enable interactive plotting with %matplotlib notebook. Then import and create a basic line plot:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.arange(10), np.arange(10)**2)
plt.show()The resulting figure appears as shown in Figure 1.
2. Subplots and Figure Layout
Create a figure and add subplots using plt.figure() and fig.add_subplot():
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)Or use the convenient plt.subplots() which returns a figure and an array of axes:
fig, axes = plt.subplots(2, 2, figsize=(8,6))Adjust spacing between subplots with fig.subplots_adjust(wspace=0.2, hspace=0.3) or plt.subplots_adjust(...). Setting both to zero removes internal gaps (see Figure 5).
3. Colors, Markers, and Line Styles
Use short format strings to specify color, marker, and line style, e.g., 'g--' for a green dashed line. For explicit arguments:
ax.plot(x, y, linestyle='--', color='g')Hex color codes (e.g., #CECECE) are also accepted. Adding markers is done by including the marker symbol in the format string or via the marker argument (see Figure 6).
4. Axes, Ticks, Labels, and Legends
Set tick positions with ax.set_xticks([0,250,500,750,1000]) and custom labels with
ax.set_xticklabels(['one','two','three','four','five'], rotation=30, fontsize='small'). Add titles and axis labels:
ax.set_title('My first matplotlib plot')
ax.set_xlabel('Stages')Legends are created by supplying a label to each plot and calling ax.legend(loc='best') (see Figure 10).
5. Annotations and Text
Add explanatory text or arrows with ax.text() and ax.annotate(). Example annotating important dates on a S&P 500 chart:
ax.annotate('Peak of bull market', xy=(date, spx.asof(date)+75),
xytext=(date, spx.asof(date)+225),
arrowprops=dict(facecolor='black', headwidth=4, width=2,
headlength=4),
horizontalalignment='left', verticalalignment='top')Zoom into a specific period with ax.set_xlim(['1/1/2007','1/1/2011']) and ax.set_ylim([600,1800]). The final annotated figure is shown in Figure 11.
6. Adding Patches (Shapes)
Matplotlib’s patches module provides geometric objects such as Rectangle, Circle, and Polygon. Create and add them to an axis:
rect = plt.Rectangle((0.2,0.75), 0.4, 0.15, color='k', alpha=0.3)
circ = plt.Circle((0.7,0.2), 0.15, color='b', alpha=0.3)
pgon = plt.Polygon([[0.15,0.15],[0.35,0.4],[0.2,0.6]], color='g', alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)Figure 12 displays the three patches.
7. Saving Figures
Export the current figure with plt.savefig('figure.png', dpi=400, bbox_inches='tight'). The format is inferred from the filename extension. To write to an in‑memory buffer:
from io import BytesIO
buf = BytesIO()
plt.savefig(buf, format='png')
image_bytes = buf.getvalue()Figure 2‑4 illustrate saved outputs in different formats.
8. Global Configuration (rc)
Adjust default properties globally with plt.rc(). Example setting a default figure size and font:
plt.rc('figure', figsize=(10,10))
font_opts = {'family':'monospace','weight':'bold','size':'small'}
plt.rc('font', **font_opts)All rc parameters are documented in the matplotlibrc file.
For a complete reference, consult the official Matplotlib documentation and the source code of the matplotlib.patches module.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
