Remove legend from patches in Matlab

2 views (last 30 days)
gummiyummi
gummiyummi on 15 Sep 2020
Answered: Steven Lord on 15 Sep 2020
I create hundreds of patches using patch() in my subplots.
I have 5 subplots, 4 of which have legend entries.
I create several figures all with patches using a for loop.
My figure with subplots + patches, comes up with not only the legend entries for the data, but also from the patches which is covering my plot!
I tried the following but nothing has worked:
% loop to create figures of the subplot with patches
for i=1:length(ix)
... % code to create plot in a figure
for j=1:length(iy) % numbering for patches
legend('off');
set(0,'DefaultLegendAutoUpdate','off');
... % code to create patches on all subplots
end
end
on other matlab questions, supposedly doing legend('off') and set(0,'DefaultLegendAutoUpdate','off') solved the problem, however it just isn't working for me. Anybody help?

Answers (1)

Steven Lord
Steven Lord on 15 Sep 2020
Specify the handles of the objects that you want to see in the legend when you create it.
x = 0:360;
axis([0 360 -1 1])
hold on
sineCurves = gobjects(1, 5);
for k = 1:5
sineCurves(k) = plot(x, sind(k*x), 'DisplayName', "sine of " + k + "*x");
end
legend(sineCurves([1 3 4]))
The curves for the sine of 2*x and 5*x appear in the plot but not in the legend.

Community Treasure Hunt

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

Start Hunting!