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
How to change the DPI of a Pandas Dataframe Plot in Matplotlib?
To change the DPI (dots per inch) of a Pandas DataFrame plot in Matplotlib, you can use rcParams to set the resolution. Higher DPI values produce sharper, more detailed plots.
What is DPI?
DPI controls the resolution of your plot. Higher DPI means more pixels per inch, resulting in sharper images. The default DPI is usually 100, but you can increase it for better quality or decrease it for smaller file sizes.
Setting DPI Using rcParams
The most common way is to set the DPI globally using matplotlib's rcParams ?
import pandas as pd
import matplotlib.pyplot as plt
# Set DPI to 150 for higher resolution
plt.rcParams["figure.dpi"] = 150
plt.rcParams["figure.figsize"] = [8, 4]
# Create sample DataFrame
data = pd.DataFrame({
"Sales": [100, 150, 120, 200, 180],
"Profit": [20, 30, 25, 45, 40]
})
# Plot the DataFrame
data.plot(kind='line', marker='o')
plt.title("Sales and Profit Over Time")
plt.show()
Setting DPI for Individual Plots
You can also set DPI for a specific figure using the dpi parameter ?
import pandas as pd
import matplotlib.pyplot as plt
# Create sample DataFrame
data = pd.DataFrame({
"Temperature": [22, 25, 28, 26, 24],
"Humidity": [60, 65, 70, 68, 62]
})
# Create figure with specific DPI
fig, ax = plt.subplots(dpi=200, figsize=(8, 4))
data.plot(ax=ax, kind='bar')
plt.title("Temperature and Humidity Data")
plt.show()
Comparison of DPI Settings
| DPI Value | Quality | File Size | Use Case |
|---|---|---|---|
| 72-100 | Standard | Small | Web display |
| 150-200 | High | Medium | Presentations |
| 300+ | Very High | Large | Print publications |
Saving High-DPI Plots
When saving plots, you can also specify DPI in the savefig() method ?
import pandas as pd
import matplotlib.pyplot as plt
# Create sample data
data = pd.DataFrame({
"Quarter": ["Q1", "Q2", "Q3", "Q4"],
"Revenue": [1000, 1200, 1100, 1300]
})
# Plot with default DPI
data.set_index('Quarter').plot(kind='pie', y='Revenue')
plt.title("Quarterly Revenue Distribution")
# Save with high DPI
plt.savefig('/tmp/revenue_chart.png', dpi=300, bbox_inches='tight')
plt.show()
Conclusion
Use plt.rcParams["figure.dpi"] to set DPI globally, or the dpi parameter in subplots() for individual plots. Higher DPI values create sharper images but larger file sizes.
