Introduction
Matplotlib is the most popular Python library for data visualization. It allows creating high-quality 2D plots, histograms, bar charts, scatter plots, and more.
It provides low-level control for fine-tuned charts while also supporting quick plotting with pyplot. This makes it suitable for exploratory analysis and publication-quality graphics.
Installation
# Using pip pip install matplotlib # Using conda conda install matplotlib
Use virtual environments for consistent dependencies, and consider installing seaborn for improved default styles.
Basic Plotting
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [10,20,25,30]
plt.plot(x, y)
plt.title('Basic Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
Basic plots are quick for exploration. For production, prefer the object-oriented API for better control.
Figure & Axes
fig, ax = plt.subplots()
ax.plot([1,2,3],[4,5,6])
ax.set_title('Axes example')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
The figure is the container, and axes are the plotting areas. This model scales cleanly to complex layouts.
Multiple Plots
plt.plot([1,2,3],[4,5,6], label='Line 1') plt.plot([1,2,3],[6,5,4], label='Line 2') plt.legend() plt.show()
Use legends, labels, and consistent color palettes to keep multiple lines readable.
Bar Chart & Histogram
# Bar chart plt.bar(['A','B','C'], [10,20,15]) plt.show() # Histogram data = [1,2,2,3,3,3,4] plt.hist(data, bins=4, color='orange', edgecolor='black') plt.show()
Histograms show distributions. Adjust bins and normalization to compare groups fairly.
Scatter & Pie Charts
# Scatter x=[5,7,8]; y=[7,9,2] plt.scatter(x, y, color='red') plt.show() # Pie sizes=[20,30,50]; labels=['A','B','C'] plt.pie(sizes, labels=labels, autopct='%1.1f%%') plt.show()
Scatter plots reveal relationships and clusters. Pie charts are best for simple part‑to‑whole comparisons.
Customization
plt.plot(x, y, color='green', linestyle='--', marker='o')
plt.title('Custom Plot', fontsize=14, color='blue')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()
Customize color, line style, markers, and annotations to improve readability and storytelling.
Subplots
fig, axs = plt.subplots(2,1) axs[0].plot([1,2,3],[4,5,6]) axs[1].bar([1,2,3],[7,8,9]) plt.show()
Subplots help compare multiple views. Use sharex and sharey for aligned axes.
Advanced Matplotlib
- 3D plotting (mpl_toolkits.mplot3d)
- Animations (FuncAnimation)
- Styles & Themes
- Integration with Pandas & Seaborn
- Logarithmic scales, twin axes
from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter([1,2,3],[4,5,6],[7,8,9]) plt.show()
Advanced features include custom projections, animations, and fine-grained control of ticks, grids, and themes.