Matplotlib.pyplot.savefig() in Python (original) (raw)

Last Updated : 03 Apr, 2025

**savefig() function in Python is used to save a plot created with Matplotlib to a file. It supports various formats like PNG, PDF, SVG, and more. This method allows you to specify additional parameters like file name, resolution, layout, and transparency, giving you control over the appearance and quality of the saved image. Example:

Python `

import matplotlib.pyplot as plt import numpy as np

x = np.linspace(0, 10, 100) y = np.sin(x)

plt.plot(x, y) plt.title('Sine Wave')

Save the plot as a PNG file

plt.savefig('sine_wave.png') plt.show()

`

**Output

sine_wave-

Saving a Sine Wave

**Explanation:

Syntax

savefig(fname, *, transparent=None, dpi=’figure’, format=None,
metadata=None, bbox_inches=None, pad_inches=0.1,
facecolor=’auto’, edgecolor=’auto’, backend=None,
**kwargs
)

**Parameters:

**Return Value: savefig() function does not return any value. It saves the figure to the specified file path and does not provide a return object. Therefore, it returns None.

Examples of Matplotlib.pyplot.savefig()

Example 1: Simple Line Plot and Saving with savefig()

This code demonstrates how to create a simple line plot using matplotlib.pyplot in Python. It plots a set of x-values (x) and y-values (y) on a graph, labels the axes, saves the plot as an image file (squares.png), and displays the plot.

Python `

import matplotlib.pyplot as plt

x =[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] y =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

plotting

plt.plot(x, y) plt.xlabel("X") plt.ylabel("Y")

plt.savefig("squares.png")

plt.show()

`

**Output

squares

Saving a Simple Line Plot

**Explanation:

Example 2: Saving a Histogram Plot with Custom Parameters

This code demonstrates how to create a histogram using matplotlib.pyplot in Python. It plots the values from the list x as a histogram, saves the figure with customized settings, and then displays the plot.

Python `

import matplotlib.pyplot as plt

x =[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] plt.hist(x)

saving the figure.

plt.savefig("squares1.png", bbox_inches ="tight", pad_inches = 1, transparent = True, facecolor ="g", edgecolor ='w', orientation ='landscape')

plt.show()

`

**Output

histogram

Saving a Histogram

**Explanation: