How to decrease the size of the legend in a figure?

aban picture aban · Nov 16, 2017 · Viewed 7.3k times · Source

The following code plots a figure. The code should work on Matlab >= R2014b. I want to remove the space within the legend. How to do this?

x = 0:0.5:10;
figure; hold on;
plot(x,sin(x), 'Marker', 'o');
plot(x,cos(x), 'Marker', 's');
[leg, objs] = legend({'sin', 'cos'}, 'Location', 'SouthWest');
line_start_end = [0.01, 0.4];
line_text_step = 0.01;
% for each line, text object, adjust their position in legend
for i = 1:numel(objs)   
  if strcmp(get(objs(i), 'Type'), 'line')
    % line object
    if 2 == numel(get(objs(i), 'XData')) % line 
      set(objs(i), 'XData', line_start_end);
    else % marker on line
      set(objs(i), 'XData', sum(line_start_end)/2);
    end
  else
    %text object
    text_pos = get(objs(i), 'Position');
    text_pos(1) = line_start_end(2) + line_text_step;
    set(objs(i), 'Position', text_pos);
  end
end

See the following result:

result

What I want is :

required

Answer

Sardar Usama picture Sardar Usama · Nov 16, 2017

There is a submission named resizeLegend by David J. Mack on File Exchange that does exactly that.

You can replace your loop with just this line:

resizeLegend(); 

which gives:

output