MATLAB : Output custom paper size figures from command-line

Matlab is great for rapid prototyping and for plotting nice figure. It is less nice when you start to demand specific things. One such thing is plotting and saving nice figure using custom size paper, position etc.

Imagine you want to obtain that nice vectorized figure saved as PDF but… on custom paper size. You don’t want to see that nasty white areas around your figure or your figure resized to fill A4 or Letter page. So, what is the solution if you want to automatise the process?

After some time messing with documentation, source code, different toolboxes (asking even more dependencies), I came up with a simple solution. All you need to know is that you can set all properties for your figure from command-line (or in the script). All the magic appears through the use of the “set” command.

Let’s assume that you just plotted a figure.

h = figure;

plot( x, y );

And you want to set it of certain size and position on the screen. First adjust the size and position of your sample figure and then get the ‘Position’ property numbers:

ps = get( h, ‘Position’ );

and then reuse it for each figure you would like to apply to:

set( gcf, ‘Position’, ps );

Now you may want to set the paper size so that you focus on your figure, with as less as possible white area around your plot. By default it’s either A4 or Legal format. If you don’t change it, your figure will be saved but will fill the whole page. This is awful for most cases, I agree. You can get the values for your adjusted test figure and set the paper size for all other figures as follows:

pps = get( h, ‘PaperSize’ );

set( h, ‘PaperSize’, pps );

“How do you adjust the paper size to match my figure size”, I hear you asking. Well, you can it in File -> Print Preview dialog of your current test figure. There you can set Width and Height of your paper and see how your figure fits there. Then you note the magic numbers and reuse them as indicated above.

Finally comes the important trick. If you don’t use it, your figure will not be in the area of your custom size paper. You will see some part of figure and plenty of white space. You need to tell MATLAB to put the figure in your new area and fill it. Do this:

set( h, ‘PaperPositionMode’, ‘auto’ );

This is it. Now you can use the standard “saveas” function and get your figure in your preferred format.

saveas( h, ‘nice_plot.pdf’ );

This is it folks. Let me know if something is not clear.

This entry was posted in Uncategorized and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *