Matplotlib Fundamentals
4. Data Visualization Techniques
Matplotlib is a powerful plotting library for Python. In this lesson, you'll learn the fundamental concepts and techniques for creating various types of plots using Matplotlib.
Matplotlib Basics
Matplotlib provides two main interfaces for creating plots: the MATLAB-like state-based interface and the object-oriented interface. We'll focus on the object-oriented approach for better control and customization.
Creating a Simple Plot
Let's start by creating a simple plot with multiple lines:
import matplotlib.pyplot as plt
import numpy as np
plt.switch_backend('Agg')
# Generate data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create the plot
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y1, label='sin(x)')
ax.plot(x, y2, label='cos(x)')
# Customize the plot
ax.set_title('Sine and Cosine Functions')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
ax.grid(True)
plt.show()
print("Plot created successfully.")
Customizing Plot Styles
Matplotlib offers various styles to change the overall look of your plots:
import matplotlib.pyplot as plt
import numpy as np
plt.switch_backend('Agg')
# Available styles
print("Available styles:", plt.style.available)
# Generate data
x = np.linspace(0, 10, 100)
y = np.exp(-x/10) * np.cos(np.pi * x)
# Create subplots with different styles
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
# Default style
ax1.plot(x, y)
ax1.set_title('Default Style')
# Seaborn style
with plt.style.context('seaborn'):
ax2.plot(x, y)
ax2.set_title('Seaborn Style')
plt.tight_layout()
plt.show()
print("Plot created successfully.")
Key Matplotlib Concepts
1. Figure: The overall window or page where everything is drawn.
2. Axes: A subplot within the figure, containing the data plot.
3. Artist: Everything visible on the figure, including Line2D, Text, or Patch objects.
4. Axis: The number-line-like objects that define plot boundaries and tick locations.
5. Spines: The lines connecting the axis tick marks that define plot boundaries.
Practice Exercises
Now it's time to apply what you've learned about Matplotlib fundamentals!
Exercise 1: Create a Line Plot
Create a line plot showing a sine wave over the interval [0, 2π].
- Data Generation: Use numpy to create x and y data for a sine wave.
- Plotting: Use plt.plot() to create the line plot.
- Customization: Add appropriate labels, title, and grid to the plot.
import numpy as np
import matplotlib.pyplot as plt
plt.switch_backend('Agg')
# Generate data
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
# Create the plot
plt.figure(figsize=(10, 6))
# Your code here to create the line plot
plt.title('___')
plt.xlabel('___')
plt.ylabel('___')
plt.grid(True)
plt.show()
print("Plot created successfully.")
Exercise 2: Create a Scatter Plot with Custom Styling
Create a scatter plot of random data points with custom colors and sizes.
- Data Generation: Use numpy to create random x and y data.
- Plotting: Use plt.scatter() to create the scatter plot.
- Customization: Set custom colors and sizes for the points.
import numpy as np
import matplotlib.pyplot as plt
plt.switch_backend('Agg')
# Generate random data
np.random.seed(0)
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = np.random.rand(50) * 1000
# Create the scatter plot
plt.figure(figsize=(10, 6))
# Your code here to create the scatter plot
plt.title('___')
plt.xlabel('___')
plt.ylabel('___')
plt.colorbar()
plt.show()
print("Plot created successfully.")
Summary
Matplotlib provides a flexible and powerful toolkit for creating a wide variety of static, animated, and interactive visualizations in Python. By mastering these fundamental concepts and techniques, you can create informative and visually appealing plots to effectively communicate your data insights. Continue experimenting with different plot types and customization options to enhance your data visualization skills.