Saving & Exporting Figures
A figure on screen disappears when you close MATLAB. For reports, slides, papers and web pages you need it as a file, at the right size, resolution and format. And when a script produces dozens of figures, saving them should happen in code, not with the mouse. Plot Formatting showed the one-line version; this lesson explains the options.
Note: saving needs a figure, so the plotting code in this lesson doesn't run in the browser. The runnable examples do the calculations around it: sizes, file names and formats.
The functions
| Function | Saves | Available in |
|---|---|---|
saveas(fig, 'name.png') |
The figure, format from the extension (or a third argument) | MATLAB, Octave |
print(fig, '-dpng', '-r300', 'name') |
The figure with a chosen device and resolution | MATLAB, Octave |
exportgraphics(obj, 'name.png', 'Resolution', 300) |
An axes or figure, tightly cropped | MATLAB R2020a+ |
copygraphics(obj) |
To the clipboard, for pasting into documents | MATLAB R2020a+ |
savefig(fig, 'name.fig') / openfig('name.fig') |
An editable figure file that reopens as a live figure | MATLAB; Octave has its own format |
frame = getframe(fig) + imwrite(frame.cdata, ...) |
The pixels currently on screen | MATLAB, Octave |
exportgraphics is the modern recommendation in MATLAB: it crops the white margin, handles resolution in one option and works on a single axes as well as a whole figure. print and saveas work in both programs, so scripts that must run in Octave use them.
Raster or vector?
| Raster (pixels) | Vector (shapes) | |
|---|---|---|
| Formats | PNG, JPEG, TIFF, BMP | PDF, EPS, SVG |
print device |
-dpng, -djpeg, -dtiff |
-dpdf, -depsc, -dsvg |
| Zooming | Gets blocky | Stays sharp at any size |
| File size | Grows with resolution | Grows with the number of objects |
| Best for | Web pages, slides, images and dense surfaces | Papers, posters, line plots, text |
Use PNG rather than JPEG for plots: JPEG compression smears thin lines and text. For a vector file from a complex 3-D surface, MATLAB may silently fall back to an image inside the PDF; exportgraphics(..., 'ContentType', 'vector') or print(..., '-vector') forces real vector output.
Size and resolution
A raster file's pixel size is its physical size times its resolution in dots per inch (dpi). Screen figures are around 96 dpi, documents usually want 300 dpi, and posters 600:
width_in = 6; height_in = 4; % the size in the document
for dpi = [96 150 300 600]
fprintf('%4d dpi -> %5d x %4d pixels (%.1f megapixels)\n', dpi, ...
width_in * dpi, height_in * dpi, width_in * height_in * dpi^2 / 1e6);
end 96 dpi -> 576 x 384 pixels (0.2 megapixels)
150 dpi -> 900 x 600 pixels (0.5 megapixels)
300 dpi -> 1800 x 1200 pixels (2.2 megapixels)
600 dpi -> 3600 x 2400 pixels (8.6 megapixels)
To get exactly that size, set the figure's paper properties before printing. They define the size of the output independently of the window on screen:
fig = figure('Units', 'inches', 'Position', [1 1 6 4]); % 6 x 4 inch window
x = linspace(0, 10, 200);
plot(x, sin(x) .* exp(-x/5), 'LineWidth', 1.5)
xlabel('Time (s)'); ylabel('Signal')
title('Measured response')
grid on
set(fig, 'PaperUnits', 'inches', 'PaperPosition', [0 0 6 4]);
print(fig, '-dpng', '-r300', 'response.png') % 1800 x 1200 pixels
print(fig, '-dpdf', 'response.pdf') % vector version
% MATLAB only: crop margins and set the resolution in one call
% exportgraphics(fig, 'response.png', 'Resolution', 300)Two details matter for good-looking exports:
- Font size scales with the paper, not the pixels. A 10-point label on a 6-inch-wide figure stays readable when the figure is placed at 6 inches in a document. If you shrink a big figure into a small space, the text shrinks too, so set the final size first and choose fonts for it (
set(gca, 'FontSize', 11)). set(fig, 'PaperPositionMode', 'auto')tellsprintto use the on-screen size instead of the paper settings, so the file looks exactly like the window.
Saving many figures from a script
Batch jobs often create one figure per data set. Three habits keep that tidy: create figures invisible so they don't flash on screen, build file names with sprintf and fullfile, and close each figure after saving it so memory doesn't fill up:
outdir = 'figures';
if ~isfolder(outdir), mkdir(outdir); end
sensors = {'north', 'east', 'south'};
for k = 1:numel(sensors)
fig = figure('Visible', 'off');
plot(1:24, k * sin((1:24) / 4))
title(['Sensor ', sensors{k}])
print(fig, '-dpng', '-r150', fullfile(outdir, sprintf('sensor_%02d_%s.png', k, sensors{k})));
close(fig)
endThe name-building part is ordinary string code, so it runs here:
outdir = 'figures';
sensors = {'north', 'east', 'south'};
for k = 1:numel(sensors)
name = fullfile(outdir, sprintf('sensor_%02d_%s.png', k, sensors{k}));
fprintf('%s\n', name);
endfigures/sensor_01_north.png
figures/sensor_02_east.png
figures/sensor_03_south.png
The %02d pads the number with zeros (01, 02, …), so the files sort correctly in a file browser even after sensor_10. fullfile inserts the right separator for the operating system (/ on Linux and macOS, \ on Windows). See Files & Folders for more about paths.
Picking the format from the file name
saveas chooses the format from the extension. With print, you can do the same thing yourself: map the extension to a device flag. A switch on the output of fileparts does it:
files = {'plot.png', 'report/fig1.pdf', 'poster.SVG', 'old.eps', 'notes.txt'};
for k = 1:numel(files)
fprintf('%-16s -> %s\n', files{k}, device_for(files{k}));
end
function dev = device_for(file)
[~, ~, ext] = fileparts(file);
switch lower(ext)
case '.png', dev = '-dpng';
case {'.jpg', '.jpeg'}, dev = '-djpeg';
case '.pdf', dev = '-dpdf';
case '.svg', dev = '-dsvg';
case '.eps', dev = '-depsc'; % colour EPS
otherwise, dev = '(not a figure format)';
end
endplot.png -> -dpng
report/fig1.pdf -> -dpdf
poster.SVG -> -dsvg
old.eps -> -depsc
notes.txt -> (not a figure format)
With that helper, print(fig, device_for(name), '-r300', name) saves any figure under any supported name. (-deps without the c gives black-and-white EPS, a classic surprise.)
Editable figures and screen captures
savefig(fig, 'result.fig')in MATLAB stores the whole figure: data, labels and styling.openfig('result.fig')brings it back as a live figure you can still edit, zoom and re-export. Octave'ssavefigandhgsavewrite Octave's own format, so don't count on exchanging.figfiles between the two programs; share the data and the script instead.frame = getframe(fig)captures the figure's pixels as an RGB array inframe.cdata, exactly as shown on screen.imwrite(frame.cdata, 'shot.png')saves it. This is also how animations are recorded (see the next lesson).
Summary
- Use
saveas/print(both programs) orexportgraphics(MATLAB) to save figures from code. - PNG for web and slides, PDF/SVG/EPS for print; avoid JPEG for plots.
- Pixel size = inches × dpi; set
PaperPosition(orPaperPositionMode'auto') to control the output size. - In batch scripts: invisible figures,
sprintf+fullfilenames,closeafter saving.
Next: Animation. Learn more: Saving figures in Matplotlib.
Test yourself
A 5-by-3 inch figure is printed with -r300. How many pixels wide is the PNG?
- 300
- 500
- 1500
- 900
Which format is best for a line plot in a printed paper?
- JPEG
- PDF or EPS (vector)
- BMP
- A screenshot
Why use sprintf('fig_%02d.png', k) in a saving loop?
- It makes the files smaller
- The zero-padded numbers keep the files in the right order when sorted by name
- print requires two-digit names
- It converts the figure to PNG