Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to better rasterize a plot without blurring the labels in matplotlib?
When creating plots in matplotlib, rasterization can help reduce file size for complex graphics, but it may blur text elements like labels. This tutorial shows how to rasterize plot elements while keeping labels crisp by selectively applying rasterization.
Understanding Rasterization
Rasterization converts vector graphics to bitmap images. While this reduces file size, it can blur text. The key is to rasterize only the plot data, not the labels ?
Example: Comparing Rasterization Settings
import matplotlib.pyplot as plt
import numpy as np
# Set figure size and layout
plt.rcParams["figure.figsize"] = [10.00, 8.00]
plt.rcParams["figure.autolayout"] = True
# Create subplots for comparison
fig, axes = plt.subplots(nrows=4, figsize=(10, 8))
fig.suptitle("Rasterization Effects on Plot Elements", fontsize=16, fontweight='bold')
# Data for plotting
x_data = np.arange(1, 10)
# Axis 0: No rasterization (vector graphics)
axes[0].fill_between(x_data, 1, 2, alpha=0.5, color='blue', rasterized=False)
axes[0].text(5, 1.5, "No Rasterization", ha='center', va='center',
fontsize=14, bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.8))
axes[0].set_title("Vector Graphics (rasterized=False)")
# Axis 1: Rasterized fill with vector text
axes[1].fill_between(x_data, 1, 2, alpha=0.5, color='green', rasterized=True)
axes[1].text(5, 1.5, "Rasterized Fill + Vector Text", ha='center', va='center',
fontsize=14, bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.8),
rasterized=False)
axes[1].set_title("Hybrid Approach (Recommended)")
# Axis 2: Everything rasterized
axes[2].fill_between(x_data, 1, 2, alpha=0.5, color='red', rasterized=True)
axes[2].text(5, 1.5, "Everything Rasterized", ha='center', va='center',
fontsize=14, bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.8),
rasterized=True)
axes[2].set_title("All Rasterized (Text May Blur)")
# Axis 3: Complex plot with selective rasterization
x_complex = np.linspace(0, 10, 1000)
y_complex = np.sin(x_complex) + 0.1 * np.random.randn(1000)
axes[3].plot(x_complex, y_complex, alpha=0.3, rasterized=True, label="Noisy data (rasterized)")
axes[3].plot(x_complex, np.sin(x_complex), linewidth=2, rasterized=False, label="Clean line (vector)")
axes[3].legend(loc='upper right', rasterized=False)
axes[3].set_title("Complex Plot with Selective Rasterization")
# Adjust spacing and show
plt.tight_layout()
plt.show()
Best Practices
Method 1: Rasterize Data, Keep Text as Vector
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(8, 6))
# Generate sample data
x = np.linspace(0, 10, 1000)
y = np.sin(x) + 0.1 * np.random.randn(1000)
# Rasterize the data plot (reduces file size)
ax.scatter(x, y, alpha=0.5, s=1, rasterized=True, label="Data points")
# Keep text elements as vectors (crisp rendering)
ax.set_xlabel("X-axis Label", fontsize=12, rasterized=False)
ax.set_ylabel("Y-axis Label", fontsize=12, rasterized=False)
ax.set_title("Optimized Rasterization Example", fontsize=14, rasterized=False)
ax.legend(rasterized=False)
plt.tight_layout()
plt.show()
Method 2: Using rcParams for Global Settings
import matplotlib.pyplot as plt
import numpy as np
# Set global rasterization threshold
plt.rcParams['path.simplify_threshold'] = 1.0
plt.rcParams['agg.path.chunksize'] = 10000
fig, ax = plt.subplots(figsize=(8, 6))
# Create complex data
x = np.linspace(0, 4*np.pi, 5000)
y = np.sin(x) * np.exp(-x/10)
# Plot with automatic rasterization for complex paths
ax.plot(x, y, linewidth=0.5, alpha=0.7, rasterized=True)
ax.fill_between(x, 0, y, alpha=0.3, rasterized=True)
# Text remains vector
ax.text(6, 0.2, "Complex waveform\n(rasterized for efficiency)",
fontsize=12, ha='center',
bbox=dict(boxstyle="round,pad=0.5", facecolor="yellow", alpha=0.7),
rasterized=False)
ax.set_title("Global Rasterization Settings", fontsize=14)
plt.show()
Key Parameters
| Parameter | Purpose | Recommendation |
|---|---|---|
rasterized=True |
Convert to bitmap | Use for complex data plots |
rasterized=False |
Keep as vector | Use for text and labels |
dpi |
Resolution for raster | 300+ for high quality |
Conclusion
For optimal results, rasterize complex plot elements like scatter plots or filled areas while keeping text elements as vectors. This approach maintains label clarity while reducing file size for complex graphics.
Advertisements
