How to change the legend format to “Descriptive text + icon”

5 Ansichten (letzte 30 Tage)
dongxu yu
dongxu yu am 6 Apr. 2025
Kommentiert: Walter Roberson am 6 Apr. 2025
I’m currently using MATLAB 2024b. By default, the legend items are displayed in the order of “icon+ Descriptive text”. I want to change it to “Descriptive text + icon”.
Here is the code provided by an AI, but it doesn’t seem to work.
x = 1:10;
y1 = x;
y2 = x.^2;
plot(x, y1, 'ro', x, y2, 'b--');
hLegend = legend('y = x', 'y = x^2');
legendTexts = findobj(hLegend, 'Type', 'text');
legendIcons = findobj(hLegend, 'Type', 'patch');
numEntries = length(legendTexts);
for i = 1:numEntries
textPosition = get(legendTexts(i), 'Position');
iconPosition = get(legendIcons(i), 'Position');
newTextX = iconPosition(1);
newIconX = textPosition(1);
set(legendTexts(i), 'Position', [newTextX, textPosition(2), textPosition(3)]);
set(legendIcons(i), 'Position', [newIconX, iconPosition(2), iconPosition(3)]);
end
Thank you in advance for your help!

Antworten (1)

Image Analyst
Image Analyst am 6 Apr. 2025
That's because legend() does not have any children, much less of types text and patch:
x = 1:10;
y1 = x;
y2 = x.^2;
plot(x, y1, 'ro', x, y2, 'b--');
hLegend = legend('y = x', 'y = x^2');
legendObjs = findobj(hLegend)
legendObjs =
Legend (y = x, y = x^2) with properties: String: {'y = x' 'y = x^2'} Location: 'northeast' Orientation: 'vertical' FontSize: 9 Position: [0.7259 0.8110 0.1607 0.0881] Units: 'normalized' Use GET to show all properties
fprintf('legend() has %d children objects.\n', numel(hLegend.Children));
legend() has 0 children objects.
And there is no option in legend to swap the positions of the text and the line/marker. You're basically either going to have to live with it, or build it yourself by editing legends.m.
If you do the latter, make sure you make a copy of legends.m in your own folder and then edit that one, not the built-in one.
builtInPath = 'C:\Program Files\MATLAB\R2024b\toolbox\matlab\graphics\graphics\scribe\legend.m';
copyfile(builtInPath, 'myLegend.m');
edit 'myLegend.m'
  2 Kommentare
dongxu yu
dongxu yu am 6 Apr. 2025
Thank you for your reply. I will just manually add a text box in the figure window to make the change.
Walter Roberson
Walter Roberson am 6 Apr. 2025
It is possible to get it to work by using the undocumented second output of legend() and fudging the Position and XData properties of the resulting exposed icons. But it is a nuisance to get right; for example you need to use the Extent property of the text objects to figure out the size of the text in order to be able to place the icon after the text. Or, I suppose, the size of the legend box could be used and some subtraction...

Melden Sie sich an, um zu kommentieren.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by