Matplotlib Mastery for Scientific Visualization

Introduction to Matplotlib

Matplotlib is the most widely used plotting library in Python, especially for scientific visualization.

Basic Plotting


import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create a simple plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', label='sin(x)')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('Simple Sine Wave')
plt.grid(True)
plt.legend()
plt.show()
                    

Publication-Quality Figures

Learn how to create professional-looking figures suitable for academic publications.

Advanced Plotting


import matplotlib.pyplot as plt
import numpy as np

# Set the style
plt.style.use('seaborn-darkgrid')

# Create figure and axis objects
fig, ax = plt.subplots(figsize=(10, 6))

# Generate data
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Plot with customization
ax.plot(x, y1, 'b-', label='sin(x)', linewidth=2)
ax.plot(x, y2, 'r--', label='cos(x)', linewidth=2)

# Customize the plot
ax.set_xlabel('x', fontsize=12)
ax.set_ylabel('y', fontsize=12)
ax.set_title('Trigonometric Functions', fontsize=14, pad=10)
ax.grid(True, linestyle='--', alpha=0.7)
ax.legend(fontsize=10)

# Adjust layout
plt.tight_layout()
                    

Multiple Subplots

Create complex figures with multiple subplots for comprehensive data visualization.

Subplot Layout


import matplotlib.pyplot as plt
import numpy as np

# Create a figure with subplots
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 10))

# Generate data
x = np.linspace(0, 5, 100)

# Plot 1: Linear
ax1.plot(x, x)
ax1.set_title('Linear')

# Plot 2: Quadratic
ax2.plot(x, x**2)
ax2.set_title('Quadratic')

# Plot 3: Cubic
ax3.plot(x, x**3)
ax3.set_title('Cubic')

# Plot 4: Square root
ax4.plot(x, np.sqrt(x))
ax4.set_title('Square Root')

# Adjust layout
plt.tight_layout()
                    

Practice Exercises

Exercise 1: Data Visualization

Create a figure showing the relationship between temperature and pressure in a gas using the ideal gas law.

Exercise 2: Error Analysis

Plot experimental data points with error bars and a theoretical curve for comparison.

Additional Resources