How to change the legend format to “Descriptive text + icon”
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Image Analyst
2025-4-6
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 个评论
Walter Roberson
2025-4-6
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...
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!