When you want to include your plots/figures in your LaTeX document, you preferably want them in vector graphics format so that they scale/print nicely in your LaTeX PDF output. Fortunately, MATLAB can render vector graphics output if you choose to save your figure in PDF format (using either the ``saveas" or the ``print" command).
One annoying thing while output PDFs of your figures is that MATLAB automatically adds white space/margin around them. So you want to get rid of them. One option is to open the PDF file in a vector graphics program (like inkspace) and cut the unwanted white space. But this becomes a problem if you have a lot of figures. So, here is an automatic way to do it. It took me sometime to figure out how to do it:
Let's go step by step. (Those who are not interested in the details and just want to get the code, skip to the bottom of this post.
One annoying thing while output PDFs of your figures is that MATLAB automatically adds white space/margin around them. So you want to get rid of them. One option is to open the PDF file in a vector graphics program (like inkspace) and cut the unwanted white space. But this becomes a problem if you have a lot of figures. So, here is an automatic way to do it. It took me sometime to figure out how to do it:
Let's go step by step. (Those who are not interested in the details and just want to get the code, skip to the bottom of this post.
- Do your plots:
x = -pi:.1:pi;
y = sin(x);
h=figure;
plot(x,y)
- Make your figure boundaries tight:
ti = get(gca,'TightInset')
set(gca,'Position',[ti(1) ti(2) 1-ti(3)-ti(1) 1-ti(4)-ti(2)]);
- Now you have a tight figure on the screen but if you directly do saveas (or print), MATLAB will still add the annoying white space. To get rid of them, we need to adjust the ``paper size":
set(gca,'units','centimeters')
pos = get(gca,'Position');
ti = get(gca,'TightInset');
set(gcf, 'PaperUnits','centimeters');
set(gcf, 'PaperSize', [pos(3)+ti(1)+ti(3) pos(4)+ti(2)+ti(4)]);
set(gcf, 'PaperPositionMode', 'manual');
set(gcf, 'PaperPosition',[0 0 pos(3)+ti(1)+ti(3) pos(4)+ti(2)+ti(4)]);
- Done! Now you can saveas your figure:
saveas(h,'output.pdf');
Or:
print -dpdf output.pdf
If you want to understand the details of step 3, you need to look at ``Position" and ``TightInset" in
Axes Properties, and ``PaperSize", ``PaperPosition" in
Figure Properties.
The code
Download here
Usage:
saveTightFigure(h,'output.pdf');
Output format can be any format that MATLAB supports: jpeg, png, eps, pdf, etc.
Enjoy.
Usage:
saveTightFigure(h,'output.pdf');
Output format can be any format that MATLAB supports: jpeg, png, eps, pdf, etc.
Enjoy.