How to save figures to pdf as raster images in Matplotlib?

To save figures to PDF as raster images in Matplotlib, you need to use the rasterized=True parameter when creating plots. This converts vector graphics to bitmap format, which can be useful for complex plots with many data points.

Basic Setup

First, let's set up the basic requirements and create a simple rasterized plot ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create figure and subplot with rasterization
fig = plt.figure()
ax = fig.add_subplot(111, rasterized=True)

# Generate random data
data = np.random.rand(5, 5)

# Display as raster image
ax.imshow(data, cmap="copper", aspect="auto", interpolation="nearest")

# Save as PDF
plt.savefig("rasterized.pdf")
plt.show()

Rasterizing Specific Plot Elements

You can also rasterize specific elements of a plot while keeping others as vectors ?

import numpy as np
import matplotlib.pyplot as plt

# Create sample data
x = np.linspace(0, 10, 1000)
y = np.sin(x) * np.exp(-x/3)

fig, ax = plt.subplots(figsize=(8, 6))

# Plot with rasterization for dense data
ax.plot(x, y, 'b-', rasterized=True, linewidth=0.5)
ax.set_title("Rasterized Plot Elements", rasterized=False)  # Keep title as vector
ax.set_xlabel("X values")
ax.set_ylabel("Y values")

plt.savefig("selective_raster.pdf", dpi=300)
plt.show()

Setting DPI for Better Quality

When saving rasterized images, specify DPI (dots per inch) for better quality ?

import numpy as np
import matplotlib.pyplot as plt

# Create complex scatter plot
np.random.seed(42)
x = np.random.randn(5000)
y = np.random.randn(5000)

fig, ax = plt.subplots(figsize=(8, 6))

# Large scatter plot - perfect for rasterization
scatter = ax.scatter(x, y, c=x+y, alpha=0.6, s=1, rasterized=True)
ax.set_title("High-DPI Rasterized Scatter Plot")

# Save with high DPI for quality
plt.savefig("high_quality_raster.pdf", dpi=300, bbox_inches='tight')
plt.show()

Key Parameters

Parameter Purpose Recommended Value
rasterized=True Convert to bitmap True for complex plots
dpi Image resolution 300 for print quality
bbox_inches='tight' Remove extra whitespace For clean output

Conclusion

Use rasterized=True for plots with many data points to reduce file size. Set dpi=300 for high-quality rasterized output. This technique is especially useful for scatter plots and heatmaps with thousands of points.

Updated on: 2026-03-25T22:58:41+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements