Comprehensive Guide to Data Visualization with Matplotlib in Python
This article provides a detailed tutorial on using Python's matplotlib library for creating 2D and 3D visualizations, covering installation, library architecture, basic plotting, line charts, bar charts, scatter plots, contour maps, image handling, and customizations with complete code examples.
Matplotlib is a powerful Python library for creating 2D and 3D visualizations, essential for data analysis and presentation. This guide walks through its installation, core architecture, and a variety of plotting techniques.
Installation
Install via conda or pip:
conda install matplotlib pip install matplotlibLibrary Architecture
Matplotlib consists of three layers: the Scripting layer (high‑level API), the Artist layer (objects representing visual elements), and the Backend layer (rendering engines). This separation enables flexible figure creation and output formats.
Basic Usage
Import the required modules and generate sample data:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 30)
y = np.sin(x)
print('x =', x)
print('y =', y)Plot a simple curve:
plt.figure()
plt.plot(x, y)
plt.show()Multiple Curves, Axes Labels, and Customization
Plot a sine curve together with a linear function, set figure size, titles, axis labels, limits, and custom tick labels:
plt.figure(figsize=(8, 6))
plt.plot(x, y)
plt.plot(x, 0.2*x + 0.1, color='red', linestyle='--')
plt.title('y = sin(x) and y = 0.2x + 0.1')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1)
xticks = np.linspace(-np.pi, np.pi, 5)
xtick_labels = [r'$\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$']
plt.xticks(xticks, xtick_labels)
plt.show()Centered Axes
Move the x‑ and y‑axes to the origin:
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
plt.show()Legends
Add labels to curves and display a legend with a chosen location:
plt.plot(x, y, label='y = sin(x)')
plt.plot(x, 0.2*x + 0.1, color='red', linestyle='--', label='y = 0.2x + 0.1')
plt.legend(loc='lower right', fontsize=12)
plt.show()The loc parameter accepts strings such as 'best', 'upper right', 'lower left', etc., as shown in the accompanying table.
Bar Charts
Create simple and side‑by‑side bar charts:
plt.figure(figsize=(16, 12))
x = np.arange(1, 9)
y = np.array([3, 5, 7, 6, 2, 6, 10, 15])
plt.plot(x, y, 'r', lw=5)
plt.bar(x, np.array([13, 25, 17, 36, 21, 16, 10, 15]), 0.2, color='b')
plt.show()For comparative bars above and below the x‑axis:
plt.bar(x, +y1, facecolor='#9999ff', edgecolor='white')
plt.bar(x, -y2, facecolor='#ff9999', edgecolor='white')
plt.xlim(-0.5, n)
plt.ylim(-1.25, 1.25)
plt.show()Scatter Plot
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2
plt.scatter(x, y, s=area, c=colors, alpha=0.8)
plt.show()Contour Plot
Generate contour lines and filled contours for a 2‑D function:
def f(x, y):
return (1 - x/2 + x**5 + y**3) * np.exp(-x**2 - y**2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
C = plt.contour(X, Y, f(X, Y), 10, colors='black', linewidths=0.5)
plt.clabel(C, inline=True, fontsize=12)
plt.contourf(X, Y, f(X, Y), 10, alpha=0.75, cmap=plt.cm.hot)
plt.show()Image Processing
Load and display an image with a colormap:
import matplotlib.image as mpimg
import matplotlib.cm as cm
img = mpimg.imread('image/fuli.jpg')
plt.imshow(img, cmap='hot')
plt.colorbar()
plt.show()Inspect the NumPy array shape and values to understand pixel data.
Matrix Image
size = 8
a = np.linspace(0, 1, size**2).reshape(size, size)
plt.figure(figsize=(16, 12))
plt.imshow(a)
plt.show()3D Plot
Create a 3‑D surface plot using Axes3D :
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(16, 12))
ax = fig.add_subplot(111, projection='3d')
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
Z = np.sqrt(X**2 + Y**2)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
plt.show()By adapting these examples to real project data, developers can produce clear, informative, and visually appealing charts and figures.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.