How to save a plot into a PDF file without a large margin around [duplicate]
What do you mean by "the proper size"? MATLAB figures are like vector graphics, so you can basically choose the size you want on your plot.
You can set the size of the paper and the position of the figure with the function set.
Example:
plot(epx(1:5));
set(gcf, 'PaperPosition', [0 0 5 5]); %Position plot at left hand corner with width 5 and height 5.
set(gcf, 'PaperSize', [5 5]); %Set the paper to have width 5 and height 5.
saveas(gcf, 'test', 'pdf') %Save figure
The above code will remove most of the borders, but not all. This is because the left-hand corner ([0 0]
in the position vector) is not the "true" left-hand corner. To remove more of the borders, you can adjust the PaperPosition
and PaperSize
vectors.
Example:
plot(exp(1:5))
set(gcf, 'PaperPosition', [-0.5 -0.25 6 5.5]); %Position the plot further to the left and down. Extend the plot to fill entire paper.
set(gcf, 'PaperSize', [5 5]); %Keep the same paper size
saveas(gcf, 'test', 'pdf')
Axes sizing in MATLAB can be a bit tricky sometimes. You are correct to suspect the paper sizing properties as one part of the problem. Another is the automatic margins MATLAB calculates. Fortunately, there are settable axes properties that allow you to circumvent these margins. You can reset the margins to be just big enough for axis labels using a combination of the Position
and TightInset
properties which are explained here. Try this:
>> h = figure; >> axes; >> set(h, 'InvertHardcopy', 'off'); >> saveas(h, 'WithMargins.pdf');
and you'll get a PDF that looks like: but now do this:
>> tightInset = get(gca, 'TightInset'); >> position(1) = tightInset(1); >> position(2) = tightInset(2); >> position(3) = 1 - tightInset(1) - tightInset(3); >> position(4) = 1 - tightInset(2) - tightInset(4); >> set(gca, 'Position', position); >> saveas(h, 'WithoutMargins.pdf');
and you'll get:
This works for displaying purposes:
set(gca(), 'LooseInset', get(gca(), 'TightInset'));
Should work for printing as well.
The script in How to get rid of the white margin in MATLAB's saveas or print outputs does what you want.
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)]);
... 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)]);