The foundational library for creating static, animated, and interactive visualizations in Python. Highly customizable and the industry standard for publication-quality figures. Use for 2D plotting, scientific data visualization, heatmaps, contours, vector fields, multi-panel figures, LaTeX-formatted plots, custom visualization tools, and plotting from NumPy arrays or Pandas DataFrames.
The foundational library for creating static, animated, and interactive visualizations in Python. Highly customizable and the industry standard for publication-quality figures. Use for 2D plotting, scientific data visualization, heatmaps, contours, vector fields, multi-panel figures, LaTeX-formatted plots, custom visualization tools, and plotting from NumPy arrays or Pandas DataFrames.
version
3.8
license
PSF
Matplotlib - Data Visualization
The most widely used library for 2D (and basic 3D) plotting. It provides full control over every element of a figure, from line styles to axis spines.
When to Use
Creating publication-quality 2D plots (Line, Scatter, Bar, Hist)
Visualizing scientific data (Heatmaps, Contours, Vector fields)
Generating complex multi-panel figures
Fine-tuning plots for papers/reports (LaTeX support)
Building custom visualization tools and dashboards
Plotting data directly from NumPy arrays or Pandas DataFrames
# Use this in a Jupyter environment or script
plt.ion() # Interactive mode on
fig, ax = plt.subplots()
line, = ax.plot([], [])
for i inrange(100):
new_data = np.random.rand(10)
line.set_data(np.arange(len(new_data)), new_data)
ax.relim()
ax.autoscale_view()
fig.canvas.draw()
fig.canvas.flush_events()
plt.pause(0.1)
3. Creating a Cluster Map / Correlation Matrix
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
corr = df.corr()
fig, ax = plt.subplots()
im = ax.imshow(corr, cmap='RdBu_r', vmin=-1, vmax=1)
ax.set_xticks(np.arange(len(corr.columns)), labels=corr.columns)
ax.set_yticks(np.arange(len(corr.index)), labels=corr.index)
# Loop over data dimensions and create text annotations.for i inrange(len(corr.index)):
for j inrange(len(corr.columns)):
text = ax.text(j, i, f"{corr.iloc[i, j]:.2f}",
ha="center", va="center", color="black")
Performance Optimization
Plotting Large Data
# 1. Use 'agg' backend for non-interactive renderingimport matplotlib
matplotlib.use('Agg')
# 2. Use PathCollection for scatter plots with many points
ax.scatter(x, y, s=1) # slow for 1M points# 3. Use marker='' (none) and only lines for speed
ax.plot(x, y, marker=None)
# 4. Decimate data before plotting
ax.plot(x[::10], y[::10]) # Plot every 10th point
Common Pitfalls and Solutions
Date/Time Axis issues
# ❌ Problem: Dates look like a black blob# ✅ Solution: Use AutoDateLocator and AutoDateFormatterimport matplotlib.dates as mdates
fig, ax = plt.subplots()
ax.plot(dates, values)
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
fig.autofmt_xdate() # Rotates labels
Multiple Legends on one plot
# ❌ Problem: Calling ax.legend() twice replaces the first one# ✅ Solution: Manually add the first artist back
fig, ax = plt.subplots()
line1, = ax.plot([1, 2], [1, 2], label='Line 1')
line2, = ax.plot([1, 2], [2, 1], label='Line 2')
first_legend = ax.legend(handles=[line1], loc='upper left')
ax.add_artist(first_legend) # Add back
ax.legend(handles=[line2], loc='lower right')
Image Saving Quality (Clipping)
# ❌ Problem: Legend or Axis title is cut off in the .png file# ✅ Solution:
fig.savefig('output.png', bbox_inches='tight')
Best Practices
Always use the OO interface (fig, ax = plt.subplots()) for scripts and modules
Save figures with appropriate formats - Use PDF/SVG for publications, PNG for web
Set DPI appropriately - 300+ for print, 72-100 for screen
Use bbox_inches='tight' when saving to prevent clipping
Close figures in loops to prevent memory leaks
Use colorblind-friendly colormaps - Avoid 'jet', prefer 'viridis', 'plasma', 'inferno'
Label all axes with descriptive names and units
Use constrained_layout=True for subplots to prevent overlap
Configure global styles with plt.rcParams for consistency