user2397472
user2397472

Reputation:

Compress the size or reduce the line spacing of a legend in matlab figures

I'm trying to make a legend in a matlab figure that takes less space, in particular vertical size. Ideally, if I could change the inter-line spacing of the legend, this would have solved it, but I can't seem to find a way to do it.

I've searched around in Mathworks questions and Google. I've even tried to "write" from scratch the legend, but it doesn't work when I try to export to eps.

Is there a way to control the inter-line spacing in Matlab's legend? something undocumented maybe?

Upvotes: 2

Views: 13399

Answers (1)

nkjt
nkjt

Reputation: 7817

One way would be to adjust the aspect ratio of the legend:

set(h,'PlotBoxAspectRatioMode','manual');
set(h,'PlotBoxAspectRatio',[1 0.8 1]);

(Default is [1 1 1]).

You can also play with the exact positioning of the various legend elements. If h is the handle for your legend:

hc = get(h,'Children');

Now, hc will be of length 3 x the number of items in your legend.

hc(1) is the marker, hc(2) is the line, hc(3) is the text.

(and so on for subsequent items).

hc(1) will have a entry YData(vertical position, single value), hc(2) also has YData (vertical position - vector of two identical values), and hc(3) contains Position - [x y z] vector. The Y values for all these three should be the same.

Obtain the y-positions:

yd = zeros(length(hc)/3,1);
for n = 1:length(yd);
  yd(n) = get(hc(1+(n-1)*3),'YData');
end

Assuming your legend doesn't have any text that goes over more than one line,yd should be evenly spaced steps. Define a new spacing of your choice, yd2.

Set new positions:

% markers
for n = 1:length(yd2)
   set(hc(1+(n-1)*3),'YData',yd2(n));
end

% lines
for n = 1:3
   set(hc(2+(n-1)*3),'YData',[yd2(n),yd2(n)]);
end

% text

for n = 1:3;
    pos = get(hc(3+(n-1)*3),'Position');
    pos(2) = yd(n);
    set(hc(3+(n-1)*3),'Position',pos);
end

Problem - this shifts all the text and markers but doesn't change the border box. The easiest way if trying to make fine adjustments is to first define the final size/position of the legend, and then reposition/resize elements within to taste.

Also, you may find that when writing out images MATLAB helpfully redraws the image, resetting your adjustments. See this blog post on Undocumented MATLAB for info on that.

Upvotes: 2

Related Questions