Matplotlib Data Visualization & Plotting

Module 5 • Session 35 • Allocation: 1 Contact Hr

matplotlib pyplot visualization subplots charts

Matplotlib is the foundation of Python's data visualization ecosystem. It provides comprehensive control over plot customization, structural layouts, and publication-quality figure generation.

1. Fundamental Architecture & Syntax

Matplotlib supports two main paradigms: the Pyplot state-based interface (quick exploratory plotting) and the Object-Oriented API (recommended for complex subplots and granular customization).

Matplotlib Function / Method Primary Chart / Purpose Key Customization Parameters
plt.plot(x, y) Line Plot color, linestyle, linewidth, marker
plt.scatter(x, y) Scatter Plot s (size), c (color/cmap), alpha (transparency)
plt.bar(x, height) Bar Chart width, color, edgecolor, align
plt.hist(data) Histogram bins, density, cumulative, alpha

Example 1: Basic Line Plot with Annotations

The code block below sets up a standard single-line plot with custom line styling, axis labels, grid lines, and a visual legend:

import matplotlib.pyplot as plt import numpy as np # Generate sample mathematical domain data x = np.linspace(0, 10, 100) y = np.sin(x) # Create plot canvas plt.figure(figsize=(8, 4)) plt.plot(x, y, color='cyan', linestyle='--', linewidth=2, label='Sine Wave sin(x)') # Labeling and customization plt.title("Sine Wave Visualizer", fontsize=14, fontweight='bold') plt.xlabel("Input X (radians)") plt.ylabel("Amplitude Y") plt.grid(True, linestyle=':', alpha=0.6) plt.legend(loc='upper right') # Render figure plt.show()
Convention Note: Standard practice imports the plotting module as import matplotlib.pyplot as plt.

2. Object-Oriented Subplots Paradigm

The object-oriented approach explicitly separates the overall figure canvas (Figure) from individual plotting panels (Axes). This provides fine-grained control when designing multi-panel figures.

import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 50) # Construct a 1-row by 2-column grid of subplots fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4)) # First panel: Line plot ax1.plot(x, x**2, color='lime', label='Quadratic x^2') ax1.set_title("Quadratic Growth") ax1.set_xlabel("X") ax1.set_ylabel("Y") ax1.legend() # Second panel: Scatter plot ax2.scatter(x, np.exp(x), color='coral', label='Exponential e^x') ax2.set_title("Exponential Growth") ax2.set_xlabel("X") ax2.set_ylabel("Y") ax2.legend() plt.tight_layout() # Optimizes spacing between subplots plt.show()

3. Key Statistical Charts: Histograms & Bar Charts

Histograms visualize continuous numerical distributions, while bar charts compare discrete categorical variables.

import matplotlib.pyplot as plt import numpy as np # 1. Bar Chart for Categories categories = ['Group A', 'Group B', 'Group C', 'Group D'] values = [42, 78, 35, 91] plt.figure(figsize=(6, 3.5)) plt.bar(categories, values, color='#3b82f6', edgecolor='white') plt.title("Category Comparisons") plt.ylabel("Scores") plt.show() # 2. Histogram for Continuous Distribution np.random.seed(42) gaussian_data = np.random.randn(1000) plt.figure(figsize=(6, 3.5)) plt.hist(gaussian_data, bins=30, color='#10b981', edgecolor='black', alpha=0.7) plt.title("Normal Distribution Histogram") plt.xlabel("Value Range") plt.ylabel("Frequency") plt.show()
Memory Warning: Always call plt.close() or plt.clf() when generating plots programmatically in loops to prevent memory leaks from accumulated figure state.

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Multi-Line Plot Comparison

Generate $x \in [0, 2\pi]$ and plot both $\sin(x)$ and $\cos(x)$ on the same axes with different line styles, colors, and a legend.

Challenge 2: Customized Scatter Plot

Generate 50 random $(x, y)$ coordinate pairs. Render a scatter plot where the marker size scales with $x$ and the marker color reflects $y$.

Challenge 3: Subplot Grid Matrix

Create a $2 \times 2$ grid of subplots displaying line, scatter, bar, and histogram charts using plt.subplots(2, 2).

⚡ Interactive Sandbox (Matplotlib Execution Engine)
Console Output:
Click "Run Code" above to render the plot...
Matplotlib Plot Output

📝 Knowledge Check Quiz

1. Which command creates a 2-row, 2-column grid of subplots using the Object-Oriented interface?
2. What parameter controls marker transparency in Matplotlib scatter plots?
3. Which function automatically adjusts subplot padding to prevent label overlapping?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)