Printing figure as pdf with long legend produces unncecessary whitespace
Show older comments
I am creating pdfs from figures with automated scripts for scientific purposes. Recently I had the need to use rather long legend entries to describe my data. When the figures are created, the plots look fine, upon printing to pdf, however, unnecessary whitespace is inserted on the right side of the legend block if the legend entries are long, which messes up my figure. It's frustrating because the figure looks fine when it is made but I wasn't able to get the exact same pdf-representation. Here's a minimal code example:
plot([0 1], [0 1]);
hold on;
plot([0 1], [1 0]);
legend('+', '-');
print(gcf, 'short.pdf', '-dpdf');
legend('A linear function with positive slope', 'A linear function with negative slope');
print(gcf, 'long.pdf', '-dpdf');
Thanks in advance.
Accepted Answer
More Answers (1)
Constantino Carlos Reyes-Aldasoro
on 20 Feb 2024
1 vote
I am not sure that I understand the problem, I tried in my computer and obtained a figure like the one below (this is jpeg, but the PDF looks the same). Can you upload your figure to show where the unnecessary space is?

2 Comments
MyNickname
on 20 Feb 2024
How strange, mine looked exactly the same without that space. OK, what you can do is to grab the handle of the legend and then manipulate the dimensions manually to make it exactly the size you want. So, first grab the handle like this:
plot([0 1], [0 1]);
hold on;
plot([0 1], [1 0]);
legend('+', '-');
print(gcf, 'short.pdf', '-dpdf');
hLegend = legend('A linear function with positive slope', 'A linear function with negative slope');
You can see the properties of the handle:
hLegend
You can now manipulate like this:
hLegend.FontName='Courier';
hLegend.Position = [0.3 0.82 0.47 0.08];
You could also remove the color of the background and edge and then you would not notice the extra space
hLegend.Color='none';
hLegend.EdgeColor='none';
Hope this helps to sort out your problem!
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

