How to save a figure remotely with pylab in Python?

Using the savefig() method of the pyplot package, we can save matplotlib figures to remote locations or specific directories by providing the complete file path.

Setting Up the Backend

When saving figures without displaying them, it's recommended to use the 'Agg' backend, which is designed for file output ?

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

Basic Figure Saving

Create a simple plot and save it to the current directory ?

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

# Create a simple plot
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.title('Sample Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Save the figure
plt.savefig("local_figure.png")
print("Figure saved as local_figure.png")
Figure saved as local_figure.png

Saving to Remote or Specific Directories

Specify the complete path to save figures in different locations ?

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

plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.title('Remote Figure')

# Save to specific directory (adjust path as needed)
plt.savefig("/path/to/remote/directory/remote_figure.png")

# Save to relative directory
plt.savefig("../figures/my_plot.png")

# Save to network drive (Windows example)
plt.savefig("//server/share/plots/network_figure.png")

Customizing Save Options

Control the quality, format, and other properties of the saved figure ?

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

plt.plot([1, 2, 3, 4], [2, 4, 1, 5])
plt.title('High Quality Figure')

# Save with custom settings
plt.savefig("high_quality_figure.png", 
           dpi=300,           # High resolution
           bbox_inches='tight', # Remove extra whitespace
           format='png',      # Specify format
           facecolor='white') # Set background color

print("High quality figure saved")
High quality figure saved

Key Parameters

Parameter Description Example
dpi Resolution in dots per inch dpi=300
bbox_inches Bounding box control 'tight'
format File format 'png', 'pdf', 'svg'
facecolor Background color 'white', 'transparent'

Conclusion

Use matplotlib.use('Agg') for non-interactive figure saving. Specify complete file paths in savefig() to save figures remotely or in specific directories with custom quality settings.

Updated on: 2026-03-25T18:04:59+05:30

631 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements