How to change the legend text without resizing the legend box

18 views (last 30 days)
For my Plot2LaTeX function I am trying to change the text of a existing legend without changing the appearance of the legend itself, e.g. boxsize, icon length etc. For previous versions of Matlab this was more or less possible, as shown below.
For the newer versions of this does not seem to work. Especially, it does not seem possible to format the the location of the elements inside the legend. Since this is not possible I a currently using some horrible and time consuming hack by padding the legend string to the appropriate length.
A minimal (not) working example is below.
%% this is how I want it to work.
figure(1);
plot(1:10,randn(1,10));
[~,dummy] = legend('A super long description with a lot of meaning and sidenotes'); % Invoke legacy
[h1,l1] = legend; % get legend handle
Pos1 = h1.Position; % size of legend
h1.String = 'Short';
drawnow
h1.Position = Pos1; % resize legend
%% But this is how it works with newer versions of matlab.
figure(2);
plot(1:10,randn(1,10));
legend('Man this is also a very long legend, how do you come up with that');
h2 = legend;% get legend handle
Pos2 = h2.Position; % size of legend
h2.String = 'Shorter';
drawnow;
h2.Position = Pos2; % resize legend
The result is a figure where the legend box has the appropriate size, but where the text and icon location have changed.
So does anybody know how to change the text of the legend without changing anything else? Or, if that is not possible, how to change the position of the text and icon within the legend? In the latter case I can update the legend manually
  2 Comments
Jan de Jong
Jan de Jong on 1 Apr 2021
Thanks for your comment. So I am trying to change the text to a shorter string without changing the appearance of the of the legend. So figure 1 is how I would like it to work but figure 2 is how it showing up with newer versions of matlab. So I would like to change the text in the legend without changing the appearance of the box.

Sign in to comment.

Answers (0)

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!