Concept Flow - Saving figures
Create plot with data
Call save function
Specify filename and format
File saved to disk
Check file exists
Done
This flow shows how a figure is created, saved to a file, and then confirmed saved.
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.savefig('myplot.png') plt.close()
| Step | Action | Input/Parameters | Result/Output |
|---|---|---|---|
| 1 | Import matplotlib.pyplot | None | Module loaded as plt |
| 2 | Create plot | x=[1,2,3], y=[4,5,6] | Plot object created with line |
| 3 | Save figure | Filename='myplot.png' | File 'myplot.png' written to disk |
| 4 | Close plot | None | Plot resources freed |
| 5 | Check file | Filename='myplot.png' | File exists on disk |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|
| plt | module loaded | plot created | file saved | plot closed | plot closed |
| filename | None | None | 'myplot.png' | 'myplot.png' | 'myplot.png' |
Saving figures in Python with matplotlib:
1. Create plot with plt.plot()
2. Save with plt.savefig('filename.ext')
3. Close plot with plt.close() to free memory
Supports formats like PNG, PDF, SVG
Always save after plotting, before closingplt.savefig() is designed to save the current figure to a file.plt.show() displays the plot, plt.plot() creates the plot, and plt.save() does not exist.plt.savefig() and it requires the filename as a string.plt.savefig('plot.png') matches this exactly.import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('myplot.pdf', dpi=300, bbox_inches='tight')import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.savefig(myplot.png)
plt.savefig('figure.png', dpi=600, bbox_inches='tight') uses dpi=600 and bbox_inches='tight' correctly. plt.savefig('figure.png', dpi=72, bbox_inches='standard') uses low dpi and invalid bbox_inches. plt.savefig('figure.png', dpi=600, bbox_inches='loose') uses bbox_inches='loose' which adds space. plt.savefig('figure.png', dpi='high', bbox_inches='tight') uses invalid dpi value 'high'.Pass the test and this pattern moves unknown