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
Is it possible to use pyplot without DISPLAY?
Yes, it is possible to use matplotlib pyplot without a display by using a non-interactive backend like Agg. This is particularly useful for server environments or headless systems where no GUI display is available.
Setting a Non-Interactive Backend
Use matplotlib.use('Agg') before importing pyplot to set a non-interactive backend ?
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
# Set figure properties
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create data
x = np.linspace(-np.pi, np.pi, 100)
# Plot data
plt.plot(x, np.sin(x) * x, c='red')
# Save figure without displaying
plt.savefig("myimage.png")
plt.close() # Close figure to free memory
print("Figure saved successfully without display!")
Figure saved successfully without display!
Using Context Manager for Memory Efficiency
For better memory management, especially when creating multiple plots, use a context manager approach ?
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
# Create multiple plots without display
for i in range(3):
fig, ax = plt.subplots(figsize=(6, 4))
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x + i)
ax.plot(x, y, label=f'sin(x + {i})')
ax.legend()
ax.set_title(f'Plot {i+1}')
plt.savefig(f"plot_{i+1}.png", dpi=150, bbox_inches='tight')
plt.close(fig) # Important: close each figure
print("All plots saved successfully!")
All plots saved successfully!
Available Non-Interactive Backends
| Backend | Output Format | Best For |
|---|---|---|
| Agg | PNG, JPEG | Raster images |
| SVG | SVG | Vector graphics |
| Publication quality | ||
| PS | PostScript | Print graphics |
Checking Current Backend
You can verify which backend is currently active ?
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
print(f"Current backend: {plt.get_backend()}")
print(f"Interactive mode: {plt.isinteractive()}")
Current backend: Agg Interactive mode: False
Conclusion
Use matplotlib.use('Agg') before importing pyplot to create plots without a display. Always call plt.close() after saving to free memory, especially when generating multiple plots programmatically.
Advertisements
