How to change the legend text without resizing the legend box
4 views (last 30 days)
Show older comments
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
Sulaymon Eshkabilov
on 1 Apr 2021
As I understood your question is that you want to change the legend text only without changing anything else. If this is the case, here is one solution:
TXT = [{"A super long description with a lot of meaning and sidenotes"};
{'Man this is also a very long legend, how do you come up with that'}];
figure(1);
plot(1:10,randn(1,10));
[~,dummy] = legend(TXT{1}); % Invoke legacy
[h1,l1] = legend; % get legend handle
Pos1 = h1.Position; % size of legend
%h1.String = TXT{1};
drawnow
h1.Position = Pos1; % resize legend
%%
figure(2);
plot(1:10,randn(1,10));
legend(TXT{2});
h2 = legend;% get legend handle
Pos2 = h2.Position; % size of legend
%h2.String =TXT{2};
drawnow;
h2.Position = Pos2; % resize legend
Answers (0)
See Also
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!