To plot multiple graphs (lines, scatter points, etc.) on a single Matplotlib plot, you can use multiple plt.plot() or ax.plot() calls before calling plt.show(). Here's how to do it, with examples:
Basic Example: Plotting Multiple Lines
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tanh(x)
# Create the plot
plt.figure(figsize=(10, 6))
# Plot each line
plt.plot(x, y1, label='Sine', color='blue', linestyle='--') # Dashed blue line
plt.plot(x, y2, label='Cosine', color='red', linestyle=':') # Dotted red line
plt.plot(x, y3, label='Tanh', color='green', marker='o', markersize=4, linestyle='') # Green circles
# Add labels and legend
plt.title('Multiple Plots on One Figure')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
# Show grid
plt.grid(True, linestyle='--', alpha=0.7)
# Display the plot
plt.show()
Key Points:
-
Multiple plt.plot() Calls:
Each call to plt.plot() adds a new line/plot to the same axes.
-
Customization:
- Colors:
color='blue' or c='b'
- Line Styles:
linestyle='--' (dashed), linestyle=':' (dotted), or linestyle='-' (solid)
- Markers:
marker='o' (circles), marker='s' (squares)
- Labels: Use
label='...' for each plot and call plt.legend() to show the legend.
Alternative: Using ax Object (Object-Oriented Approach)
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y1, label='Sine', color='blue')
ax.scatter(x, y2, label='Cosine', color='red', marker='x') # Scatter plot for y2
ax.plot(x, y3, label='Tanh', color='green', linestyle='--')
ax.set_title('Multiple Plots with ax Object')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.legend()
ax.grid(True)
plt.show()
Plotting Different Types of Charts Together
You can mix line plots, scatter plots, bar charts, etc., on the same axes:
# Example with a bar chart and line
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 12, 67]
line_x = np.arange(len(categories))
line_y = [x**0.5 for x in values]
plt.figure(figsize=(8, 5))
plt.bar(categories, values, label='Bar Data', color='skyblue')
plt.plot(line_x, line_y, marker='o', color='orange', linewidth=2, label='Line Data')
plt.title('Bars and Line on Same Plot')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.legend()
plt.show()