0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Set DPI in Matplotlib for Clearer Plots

You can set the dpi in Matplotlib by passing the dpi parameter to plt.figure() or plt.savefig(). This controls the resolution of the plot in dots per inch, making images sharper or larger.
๐Ÿ“

Syntax

To set the DPI in Matplotlib, use the dpi parameter in these common places:

  • plt.figure(dpi=VALUE): Sets the resolution of the figure when displayed.
  • plt.savefig('filename.png', dpi=VALUE): Sets the resolution when saving the figure to a file.

Here, VALUE is an integer representing dots per inch (e.g., 100, 200, 300).

python
import matplotlib.pyplot as plt

# Set DPI when creating a figure
plt.figure(dpi=150)

# Set DPI when saving a figure
plt.savefig('plot.png', dpi=300)
๐Ÿ’ป

Example

This example shows how to create a plot with a higher DPI for clearer display and save it with an even higher DPI for better quality in the saved image.

python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create figure with DPI 120
plt.figure(dpi=120)
plt.plot(x, y)
plt.title('Sine Wave with DPI=120')
plt.show()

# Save the figure with DPI 300
plt.savefig('sine_wave_high_dpi.png', dpi=300)
Output
A plot window appears showing a sine wave with clear resolution due to dpi=120. The saved file 'sine_wave_high_dpi.png' has higher resolution (dpi=300).
โš ๏ธ

Common Pitfalls

Common mistakes when setting DPI include:

  • Setting DPI only in plt.savefig() but not in plt.figure(), which affects on-screen display quality.
  • Using very low DPI values (like 50), which makes plots blurry.
  • Forgetting to set DPI when saving, resulting in low-quality images.

Always set DPI explicitly where needed to control both display and saved image quality.

python
import matplotlib.pyplot as plt

# Wrong: No DPI set, default low quality
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('low_quality.png')

# Right: Set DPI when saving for better quality
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('high_quality.png', dpi=300)
๐Ÿ“Š

Quick Reference

MethodPurposeExample
plt.figure(dpi=VALUE)Set resolution for on-screen figureplt.figure(dpi=150)
plt.savefig('file.png', dpi=VALUE)Set resolution when saving imageplt.savefig('plot.png', dpi=300)
โœ…

Key Takeaways

Set DPI in plt.figure() to control on-screen plot resolution.
Set DPI in plt.savefig() to control saved image quality.
Higher DPI means clearer and larger images but bigger file size.
Always specify DPI explicitly to avoid blurry plots.
Typical DPI values are 100, 150, 300 depending on use case.