0
0
Matplotlibdata~5 mins

Agg backend for speed in Matplotlib

Choose your learning style9 modes available
Introduction

The Agg backend in matplotlib helps create images faster by drawing plots directly to a file or memory without showing them on screen.

When you want to save plots as image files quickly without displaying them.
When running scripts on a server or computer without a screen (headless environment).
When generating many plots automatically and speed is important.
When you only need the plot images for reports or web pages, not interactive viewing.
Syntax
Matplotlib
import matplotlib
matplotlib.use('Agg')

Use matplotlib.use('Agg') before importing pyplot to set the backend.

This backend does not open any window or GUI, so it is faster for saving files.

Examples
This example sets the Agg backend, creates a simple line plot, and saves it as 'plot.png' without showing it.
Matplotlib
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('plot.png')
Here, a bar chart is created and saved quickly using the Agg backend.
Matplotlib
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.bar([1, 2, 3], [3, 7, 5])
plt.savefig('bar_chart.png')
Sample Program

This program uses the Agg backend to create and save a plot image file without opening any window. It prints a confirmation message.

Matplotlib
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

# Create a simple plot
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
plt.plot(x, y)

# Save the plot to a file
plt.savefig('sample_plot.png')

# Confirm file saved by printing message
print('Plot saved as sample_plot.png')
OutputSuccess
Important Notes

Always set the backend before importing matplotlib.pyplot.

The Agg backend is best for scripts that only save images, not for interactive use.

Summary

The Agg backend speeds up plot saving by not showing windows.

Use it in scripts or servers where you only need image files.

Set it before importing pyplot to avoid errors.