matplotlib
  1. matplotlib-saving-figures

Saving Figures - ( Exporting and Saving Plots )

Heading h2

Syntax

plt.savefig(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None,
        transparent=False, bbox_inches=None, pad_inches=0.1,
        frameon=None, metadata=None)

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y = np.sin(x)

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

plt.savefig('sine_wave.png')

Output

A PNG image file named sine_wave.png is saved in the current working directory.

Explanation

In data visualization, it is often required to save the plotted figure in a file format like PNG, JPEG, PDF, etc. With Matplotlib's savefig() function, we can save the current figure to a file.

The savefig() function takes in the filename as the argument and optional parameters like the DPI (dots per inch), the figure size, and the file format.

In the above example, we first plot the sine wave using the plot() function, and then we set the axis labels and the title using the xlabel(), ylabel(), and title() functions respectively. Finally, we save the figure as a PNG file using the savefig() function.

Use

Saving figures is useful in various data visualization applications where we need to share the created plots with others, include them in reports or presentations, or use them in web applications.

Important Points

  • Matplotlib's savefig() function can be used to save the current figure to a file
  • The function takes in the filename as the argument and optional parameters like DPI, figure size, and file format
  • It is useful to save the created plots in various data visualization applications

Summary

In conclusion, Matplotlib's savefig() function is a useful feature for saving the created plots in various formats like PNG, JPEG, PDF, etc. It is important for sharing the plotted figures with others or including them in reports, presentations, or web applications.

Published on: