Open In App

How to Create Matplotlib Plots Without a GUI

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Method 1: Using Non-Interactive Backends - (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:

Python
import matplotlib
matplotlib.use('Agg')  # Use the 'Agg' backend for non-GUI rendering
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('plot.png')  # Save the plot as a PNG file
plt.close()  # Close the plot to free up memory

Method 2: Saving Plots with savefig

The 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')

Method 3: Set the backend via the matplotlibrc configuration

You 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())

Method 4: Turning Off Interactive Mode

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:

Python
import matplotlib.pyplot as plt

# Turn off interactive mode
plt.ioff()
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("Interactive Mode Disabled")

# The plot won't display automatically Save the plot instead
plt.savefig("plot.png")

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')

Key Takeaways:

  • 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.


Next Article

Similar Reads