Core Concepts and Library Basics
Matplotlib is the foundational library for static, animated, and interactive visualizations in Python. It provides an object-oriented API that allows for precise control over every element of a figure.
Fundamental Functions and Workflow
The standard approach involves importing the pyplot module and using the object-oriented interface for better scalability.
import matplotlib.pyplot as plt
import numpy as np
# Basic line generation
points_x = np.linspace(0, 10, 50)
points_y = points_x ** 2
fig, ax = plt.subplots()
ax.plot(points_x, points_y, label='Quadratic Trend')
ax.set_xlabel('Time (s)')
ax.set_ylabel('Velocity (m/s)')
ax.set_title('Motion Over Time')
ax.legend()
plt.show()
Essential Visualization Types
1. Scatter Plots
Scatter plots are used to identify correlations between two continuous variables. Use ax.scatter to visualize distribution patterns.
coord_x = np.random.randn(200)
coord_y = np.random.randn(200)
plt.scatter(coord_x, coord_y, alpha=0.6, c='purple', edgecolors='none', s=30)
plt.title('Random Normal Distribution')
plt.show()
2. Bar and Categorical Charts
Bar charts compare discrete categories. The bar function handles vertical orientation, while barh handles horizontal.
subjects = ['Python', 'C++', 'Java', 'Go']
popularity = [95, 70, 65, 80]
plt.bar(subjects, popularity, color='teal', width=0.6)
plt.ylabel('Adoption Rate (%)')
plt.title('Programming Language Trends')
plt.show()
3. Histograms
Histograms display the frequency distribution of a single dataset by grouping values into bins.
samples = np.random.normal(100, 15, 5000)
plt.hist(samples, bins=40, color='orange', alpha=0.8, rwidth=0.9)
plt.title('Observation Frequency')
plt.grid(axis='y', alpha=0.3)
plt.show()
Advanced Data Representations
Heatmaps and Matrix Visualization
Heatmaps represent 2D data using color scales, ideal for correlation matrices or spatial density.
grid_data = np.random.rand(12, 12)
plt.imshow(grid_data, cmap='viridis', interpolation='bilinear')
plt.colorbar(label='Intensity Scale')
plt.title('Spatial Heatmap Simulation')
plt.show()
Box-and-Whisker Plots
These are critical for statistical analysis, showing the median, quartiles, and potential outliers.
group_a = [np.random.normal(50, 5) for _ in range(50)]
group_b = [np.random.normal(55, 10) for _ in range(50)]
plt.boxplot([group_a, group_b], labels=['Group A', 'Group B'], patch_artist=True)
plt.title('Statistical Variance Comparison')
plt.show()
Pie and Donut Charts
Pie charts represent part-to-whole relationships.
segments = [40, 25, 20, 15]
segment_labels = ['Engineering', 'Marketing', 'Sales', 'Admin']
plt.pie(segments, labels=segment_labels, autopct='%1.1f%%', explode=[0.1, 0, 0, 0])
plt.title('Departmental Resource Allocation')
plt.show()
Layout Management and Subplots
Constructing complex layouts is achieved through plt.subplot or the more flexible plt.subplots grid system.
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
# Left subplot
ax1.plot([1, 2, 3], [10, 20, 10], color='red')
ax1.set_title('Primary Metric')
# Right subplot
ax2.bar(['X', 'Y'], [5, 12], color='blue')
ax2.set_title('Secondary Comparison')
plt.tight_layout()
plt.show()
Specialty and High-Dimensional Plots
Polar Coordinates
Polar plots are useful for cyclical or directional data.
radians = np.linspace(0, 2 * np.pi, 200)
radius = np.abs(np.cos(3 * radians))
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax.plot(radians, radius, color='green')
ax.set_title("Rose Curve Analysis")
plt.show()
3.3D Surface Projection
Visualizing 3D data requires the mplot3d toolkit, which is included with Matplotlib.
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
val_x = np.outer(np.linspace(-2, 2, 30), np.ones(30))
val_y = val_x.copy().T
val_z = np.cos(val_x ** 2 + val_y ** 2)
ax.plot_surface(val_x, val_y, val_z, cmap='magma')
ax.set_title('3D Wave Surface')
plt.show()
Vector Fields (Quiver Plots)
Quiver plots display direction and magnitude of vectors across a 2D plane.
mesh_x, mesh_y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .2))
vector_u = np.cos(mesh_x) * mesh_y
vector_v = np.sin(mesh_y) * mesh_x
plt.quiver(mesh_x, mesh_y, vector_u, vector_v, color='darkblue')
plt.title('Fluid Flow Simulation')
plt.show()
Formatting and Exporting
Visual style can be globally modified using plt.style.use(). Common styles include ggplot, seaborn-v0_8, and fivethirtyeight. To save high-resolution graphics for publication, use savefig with appropriate DPI settings.
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('report_figure.pdf', format='pdf', dpi=300, bbox_inches='tight')