Controlling the size of legend markers separately from the font size of legend labels
Show older comments
I need to control the markers in my legend separately from the font size of the legends' labels. Inspired by this previous answer, I used this code, in Matlab 2016a:
x = 1:10;
plot(x, 1*x, 'o')
hold on
plot(x, 2*x, 's')
h_legend = legend({'one','two'});
objhl = findobj(h_legend, 'type', 'line'); % objects of legend of type patch
set(objhl, 'Markersize', 99); % set marker size as desired
Funnily enough, this solution worked for me for a few plots. However, after a while, now whatever I type in place of the 99, makes no difference. If I change the 'line' into 'patch, that also makes no difference. The problem I guess comes from the fact that objhl is actually empty:
>> objhl = findobj(h_legend, 'type', 'patch')
objhl =
0x0 empty GraphicsPlaceholder array.
Any thoughts? Many thanks!
Accepted Answer
More Answers (1)
This solution avoids the use of undocumented legend outputs that have caused problems in the past (example 1, example 2).
% Plot data
x = 1:10;
plot(x, 1*x, 'bo');
hold on;
plot(x, 2*x, 'rs');
% Create customizable objects that won't appear on the axes
% but will appear in the legend
h(1) = plot(nan, nan, 'bo', 'MarkerSize', 15, 'DisplayName', 'one');
h(2) = plot(nan, nan, 'rs', 'MarkerSize', 15, 'DisplayName', 'two');
legend(h)
4 Comments
Subhadeep Koley
on 6 Feb 2020
@ Adam Danz Nice solution!
The code above changed the marker's color. So I have used this code which is almost the same:
Matlab R2019b
f12=figure('Name', 'Plot_name', 'visible','off');
hold on;
plot(data(1,:), data(74,:), 'linestyle','none','marker','o', 'MarkerSize', 0.5, 'color', '#000080');
plot(data(1,:), data(75,:), 'linestyle','none','marker','o', 'MarkerSize', 0.5, 'color', '#000000');
plot(data(1,:), data(76,:), 'linestyle','none','marker','o', 'MarkerSize', 0.5, 'color', '#6897bb');
xlabel('Time in s');
ylabel('Est. M. F.');
axis([-inf inf 0 1.1]);
grid on;
box on;
% legend
h(1)=plot(nan, nan, 'o', 'MarkerSize', 5, 'DisplayName', 'Est. H20', 'color', '#000080');
h(2)=plot(nan, nan, 'o', 'MarkerSize', 5, 'DisplayName', 'Est. H2', 'color', '#000000');
h(3)=plot(nan, nan, 'o', 'MarkerSize', 5, 'DisplayName', 'Est. N2', 'color', '#6897bb');
legend(h, 'Location','east');
Adam Danz
on 30 Mar 2022
> The code above changed the marker's color.
Are you refering to the code from my answer? That only changes marker size, not marker color.
Francesco Bernardini
on 21 Jul 2023
Amazing! Thanks a lot
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!
