![]() |
VOOZH | about |
To create and save plots using Matplotlib without opening a GUI window, you need to configure Matplotlib to use a non-interactive backend. This can be achieved by setting the backend to 'Agg', which is suitable for generating plots without displaying them. Let's see how to set the backend to Agg:
Non-interactive backends like 'Agg' allow you to render plots without opening a GUI window. This is crucial for automation and running scripts on headless servers where GUI support is unavailable. To use a non-interactive backend, set it at the beginning of your script:
savefigThe savefig function is essential for saving plots directly to files without displaying them. It supports various formats like PNG, PDF, SVG, etc., making it versatile for different use cases.After plotting your data, use plt.savefig('filename.ext') to save the plot:
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('plot.png')
matplotlibrc configurationYou can also set the backend globally by modifying the matplotlib configuration file (matplotlibrc), or by passing the backend argument directly when importing: Locate or create the matplotlibrc file. You can find the location using:
import matplotlib
print(matplotlib.matplotlib_fname())
Disabling interactive mode with plt.ioff() prevents plots from being displayed automatically. This is useful when you want complete control over when and how plots are shown or saved. To turn off interactive mode:
If you don't want any GUI interaction and just want to save the plot directly to a file, you can use savefig() without needing to call show(). This is particularly useful in automated scripts.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.savefig('plot.png')
Agg backend: Use this for a non-interactive, non-GUI backend.savefig(): Save plots directly to files without needing to show them.Using Agg is ideal for automated or server-side plotting where you don't need to display the plot interactively.