Save Plot with Minimal White Space

This example shows how to programmatically save plots in a figure so that the saved plot has a tight margin of white space around the axes.

Alternatively, you can interactively save a plot with minimal white space using the export button in the axes toolbar. The toolbar appears when you hover over the axes. When you save axes using the export button, the saved output is tightly cropped around the axes content, including any legends or colorbars. The output does not include content that is not related to the axes, such as UI controls or other axes in the figure.

Create Plot to Save

Create a plot to save and add a title.

plot(peaks)
title('Plot of Peaks Function')

Expand Axes to Fill Figure

Expand the axes size so that it fills the maximum available space in the figure. Get the dimensions of the maximum available space from the OuterPosition property of the axes. Account for the space needed for the tick values and text labels using the margin values stored in the TightInset property.

ax = gca;
outerpos = ax.OuterPosition;
ti = ax.TightInset; 
left = outerpos(1) + ti(1);
bottom = outerpos(2) + ti(2);
ax_width = outerpos(3) - ti(1) - ti(3);
ax_height = outerpos(4) - ti(2) - ti(4);
ax.Position = [left bottom ax_width ax_height];

Alternatively, you can interactively expand the size of the axes to fill the figure using the File > Export Setup dialog. In the Properties section, select Size, and then select Expand axes to fill figure. This option only affects axes with an ActivePositionProperty property set to 'outerposition'.

Note

To display multiple plots in a figure with minimal white space, call the tiledlayout function. Specify each of the 'Padding' and 'Spacing' name-value pair arguments as 'none'.

Specify Figure Size and Page Size

Set the page size equal to the figure size to ensure that there is no extra whitespace. This step is necessary only if you are saving to a PDF or PostScript® file format. If you are saving to an image file format, this step is not necessary. Image formats automatically use a page size that fits tightly around the saved figure.

fig = gcf;
fig.PaperPositionMode = 'auto'
fig_pos = fig.PaperPosition;
fig.PaperSize = [fig_pos(3) fig_pos(4)];

Save Figure to File Format

Save the figure to a file.

print(fig,'MySavedFile','-dpdf')

See Also

|

Related Topics