Matplotlib is a powerful plotting library in Python used for 2D graphics. It allows users to create static, animated, and interactive visualizations in Python.
Whether you're doing data analysis or building dashboards, mastering Matplotlib is an essential skill.
What You Will Learn
-
What is Matplotlib?
-
Installing Matplotlib
-
Basic Structure of a Plot
-
Common Plot Types
-
Customizing Plots
-
Saving Plots
-
Complete Code Example
-
Tips and Common Pitfalls
Installing Matplotlib
If you haven’t installed Matplotlib yet, you can do so using pip:
pip install matplotlib
Or in Jupyter notebooks:
!pip install matplotlib
Basic Structure of a Plot
The core component of Matplotlib is pyplot
, typically imported like this:
import matplotlib.pyplot as plt
A basic plot involves:
-
Defining data
-
Creating the plot
-
Customizing the appearance
-
Displaying the plot
Step-by-Step Example: A Simple Line Plot
import matplotlib.pyplot as plt
# Step 1: Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Step 2: Create the plot
plt.plot(x, y)
# Step 3: Customize
plt.title("Simple Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
# Step 4: Show the plot
plt.show()
What Just Happened?
-
plt.plot(x, y)
creates a line chart. -
plt.title()
,plt.xlabel()
, andplt.ylabel()
add context to your graph. -
plt.show()
renders the plot.
Common Plot Types
1. Bar Chart
categories = ['A', 'B', 'C']
values = [5, 7, 3]
plt.bar(categories, values)
plt.title("Bar Chart")
plt.show()
2. Scatter Plot
x = [1, 2, 3, 4]
y = [10, 15, 13, 17]
plt.scatter(x, y)
plt.title("Scatter Plot")
plt.show()
3. Histogram
data = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
plt.hist(data, bins=5)
plt.title("Histogram")
plt.show()
4. Pie Chart
labels = ['Python', 'Java', 'C++', 'Ruby']
sizes = [215, 130, 245, 210]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Programming Language Usage")
plt.show()
Customizing Plots
Change Line Style and Color
plt.plot(x, y, color='green', linestyle='--', marker='o')
Set Figure Size
plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.show()
Add Grid
plt.grid(True)
Add Legend
plt.plot(x, y, label='Prime Growth')
plt.legend()
Saving the Plot
plt.savefig('my_plot.png', dpi=300)
This saves the current figure to a file.
✅ Complete Code Example
Here’s a complete script that uses multiple features of Matplotlib:
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 2, 3, 4, 5]
# Create figure and axes
plt.figure(figsize=(10, 6))
# Plot lines
plt.plot(x, y1, label='Squared', color='blue', linestyle='-', marker='o')
plt.plot(x, y2, label='Linear', color='red', linestyle='--', marker='x')
# Titles and labels
plt.title('Line Comparison')
plt.xlabel('X Values')
plt.ylabel('Y Values')
# Grid, Legend, Save
plt.grid(True)
plt.legend()
plt.savefig('comparison_plot.png', dpi=300)
# Display
plt.show()
Tips for Using Matplotlib
-
Always label your axes and title – It adds meaning to your plots.
-
Use
plt.figure()
when creating multiple plots – Helps avoid overlap. -
Use
plt.tight_layout()
– Automatically adjusts subplot spacing. -
Test in Jupyter Notebooks – The
%matplotlib inline
magic command renders plots inline. -
Try Seaborn for advanced styling – It’s built on top of Matplotlib.
⚠️ Common Pitfalls
Pitfall | Solution |
---|---|
Forgetting plt.show() |
The plot won’t render unless shown explicitly (outside Jupyter). |
Overlapping plots | Use plt.clf() or plt.figure() to clear or separate figures. |
Incorrect data types | Make sure you pass lists, NumPy arrays, or Pandas series. |
Saving before plt.show() |
Always call plt.savefig() before plt.show() . |
Cluttered plots | Avoid plotting too many things at once—use subplots. |
Conclusion
Matplotlib is a robust and flexible tool for data visualization in Python. Whether you're plotting simple lines or complex figures, knowing how to use Matplotlib will make your data analysis much more insightful.
Want to go further? Look into:
-
plt.subplot()
for multiple plots in one figure -
matplotlib.animation
for animated plots -
Axes3D
for 3D visualizations