How to change the legend format to “Descriptive text + icon”
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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!
0 Kommentare
Antworten (1)
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)
fprintf('legend() has %d children objects.\n', numel(hLegend.Children));
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
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...
Siehe auch
Kategorien
Mehr zu Legend finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!