How to get rid of the white margin in MATLAB's saveas or print outputs

website   http://tipstrickshowtos.blogspot.com/2010/08/how-to-get-rid-of-white-margin-in.html
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. 


  1. Do your plots:

    x = -pi:.1:pi;
    y = sin(x);
    h=figure;
    plot(x,y)
  2. 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)]);
  3. 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)]);
  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. 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值