Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tight bounding box around PDF of MATLAB figure

When creating a simple figure in MATLAB and saving it as PDF, the resulting PDF file will have a luxurious bounding box.

plot(1,1,'x')
print(gcf, '-dpdf', 'test.pdf');

(From the ratio of the output it seems they always put in on an A page.)

Is there a simple way to get a tight bounding box around the PDF?

like image 503
Nico Schlömer Avatar asked Aug 28 '12 13:08

Nico Schlömer


People also ask

How do you remove a bounding box in Matlab?

bboxB = bboxerase( bboxA , window ) removes bounding boxes in the input bboxA that lie within a region of interest (ROI) specified by window . The output is the set of bounding boxes retained from the input bboxA .

How do you make a bounding box in Matlab?

Description. [ xlim , ylim ] = boundingbox( polyin ) returns the x and y bounds of the smallest rectangle enclosing a polyshape . xlim and ylim are two-element row vectors whose first elements correspond to the lower x and y bounds, and whose second elements correspond to the upper x and y bounds.

How do I save a Matlab file as a PDF?

Click the drop-down menu next to "Save as type" and select "PDF." Type in a name for the PDF file.


2 Answers

An old question, but I'll answer since google found this for me before the Mathworks own help page (Sorry no reputation enough to post a comment to previous). Anyway

ratio = (ps(4)-ps(2)) / (ps(3)-ps(1))

should be

ratio = ps(4)/ps(3);

as first values gcf.Position are [x,y] location on the screen, nothing to do with the size.

Also Matlab(R) gives an answer, especially if you don't want/need to resize figure: https://se.mathworks.com/help/matlab/creating_plots/save-figure-with-minimal-white-space.html

fig = gcf;
fig.PaperPositionMode = 'auto'
fig_pos = fig.PaperPosition;
fig.PaperSize = [fig_pos(3) fig_pos(4)];
like image 32
Space47 Avatar answered Sep 20 '22 05:09

Space47


You can format the bounding box as follows

figure(1)
hold on;
plot(1,1,'x')

ps = get(gcf, 'Position');
ratio =  ps(4) / ps(3)
paperWidth = 10;
paperHeight = paperWidth*ratio;


set(gcf, 'paperunits', 'centimeters');
set(gcf, 'papersize', [paperWidth paperHeight]);
set(gcf, 'PaperPosition', [0    0   paperWidth paperHeight]);


print(gcf, '-dpdf', 'test2.pdf');

For smaller borders, you can adjust the paperposition property, e.g.

set(gcf, 'PaperPosition', [-0.5   -0.5   paperWidth+0.5 paperHeight+0.5]);

~edit~

I corrected the calculation of the ratio because it was wrong, as pointed out by Space47's answer. (Thanks @Space47).

like image 98
H.Muster Avatar answered Sep 23 '22 05:09

H.Muster