What is Matplotlib?
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. It's the foundation for most Python plotting libraries.
Installation
Install Matplotlib:
pip install matplotlib
Basic Plot
Create your first plot:
import matplotlib.pyplot as plt
# Simple line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.show()
Figure and Axes
Use object-oriented approach (recommended):
import matplotlib.pyplot as plt
fig, ax = plt.subplots() # Create figure and axes
ax.plot([1, 2, 3, 4], [1, 4, 9, 16])
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_title('My Plot')
plt.show()
Multiple Plots
Create subplots:
fig, axes = plt.subplots(2, 2) # 2x2 grid
axes[0, 0].plot([1, 2, 3], [1, 2, 3])
axes[0, 1].plot([1, 2, 3], [1, 4, 9])
axes[1, 0].bar(['A', 'B', 'C'], [1, 2, 3])
axes[1, 1].scatter([1, 2, 3], [1, 4, 9])
plt.tight_layout() # Adjust spacing
plt.show()
Customizing Plots
Customize appearance:
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 9, 16],
color='blue', # Line color
linestyle='--', # Line style
linewidth=2, # Line width
marker='o', # Marker style
markersize=8, # Marker size
label='Data') # Legend label
ax.set_xlabel('X Label', fontsize=12)
ax.set_ylabel('Y Label', fontsize=12)
ax.set_title('Plot Title', fontsize=14)
ax.legend() # Show legend
ax.grid(True) # Show grid
plt.show()
Saving Plots
Save plots to files:
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
# Save as PNG
plt.savefig('plot.png')
# Save as PDF
plt.savefig('plot.pdf')
# High resolution
plt.savefig('plot.png', dpi=300)
# With specific size
fig.set_size_inches(10, 6)
plt.savefig('plot.png')
Common Plot Types
Different visualization types:
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# Line plot
axes[0, 0].plot([1, 2, 3], [1, 4, 9])
axes[0, 0].set_title('Line Plot')
# Bar chart
axes[0, 1].bar(['A', 'B', 'C'], [3, 7, 2])
axes[0, 1].set_title('Bar Chart')
# Scatter plot
axes[1, 0].scatter([1, 2, 3, 4], [2, 4, 1, 3])
axes[1, 0].set_title('Scatter Plot')
# Histogram
axes[1, 1].hist([1, 2, 2, 3, 3, 3, 4, 4, 5])
axes[1, 1].set_title('Histogram')
plt.tight_layout()
plt.show()
Styling
Use built-in styles:
# Available styles
print(plt.style.available)
# Apply style
plt.style.use('seaborn-v0_8-darkgrid')
# Or use context manager
with plt.style.context('dark_background'):
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
Best Practices
- Use object-oriented API: More flexible and powerful
- Set figure size early: Before plotting
- Add labels and titles: Make plots self-explanatory
- Use tight_layout(): Prevent label overlap
- Save with high DPI: For publication quality
Next Steps
Learn about line plots, bar charts, or scatter plots in detail.