0
0
Data Analysis Pythondata~5 mins

Saving figures in Data Analysis Python

Choose your learning style9 modes available
Introduction

Saving figures lets you keep your charts and graphs as image files. This helps you share or use them later without re-creating them.

You want to include a chart in a report or presentation.
You need to save a graph to show your work to others.
You want to keep a backup of your analysis visuals.
You want to compare different charts side by side later.
You want to publish your graphs on a website or blog.
Syntax
Data Analysis Python
plt.savefig('filename.png', dpi=300, bbox_inches='tight')

filename.png is the name and format of the saved file.

dpi controls the image quality (dots per inch).

Examples
Saves the current figure as a PNG file named 'chart.png' with default settings.
Data Analysis Python
plt.savefig('chart.png')
Saves the figure as a PDF file with 200 dpi resolution.
Data Analysis Python
plt.savefig('plot.pdf', dpi=200)
Saves the figure as a JPG file and trims extra white space around the image.
Data Analysis Python
plt.savefig('graph.jpg', bbox_inches='tight')
Sample Program

This code creates a simple line plot and saves it as 'line_plot.png' with 150 dpi quality. The bbox_inches='tight' trims extra space around the plot.

Data Analysis Python
import matplotlib.pyplot as plt

# Create a simple line plot
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.title('Simple Line Plot')

# Save the figure as a PNG file
plt.savefig('line_plot.png', dpi=150, bbox_inches='tight')

print('Figure saved as line_plot.png')
OutputSuccess
Important Notes

Always call plt.savefig() before plt.show() because showing the plot can clear it.

You can save figures in many formats like PNG, JPG, PDF, SVG by changing the file extension.

Use dpi to control image clarity; higher dpi means better quality but larger file size.

Summary

Use plt.savefig() to save your plots as image files.

Choose file format by the file extension you provide.

Set dpi and bbox_inches to control quality and layout.