How to remove legend entries from saved .fig file?

4 views (last 30 days)
I know that legend enteries can be specified with
legend([p1 p3],{'First','Third'})
provided you have plotted it with corresponding names:
x = linspace(0,pi);
y1 = cos(x);
p1 = plot(x,y1);
hold on
y2 = cos(2*x);
p2 = plot(x,y2);
y3 = cos(3*x);
p3 = plot(x,y3);
hold off
But if I open a saved .fig file without those p1 and p2 names assigned to plots, how can I use same trick?
Thank you
UPD: I have diferrent plot 'types' (errorbars and lines)

Accepted Answer

Star Strider
Star Strider on 27 Sep 2021
Edited: Star Strider on 27 Sep 2021
One approach —
figure;
x = linspace(0,pi);
y1 = cos(x);
p1 = plot(x,y1);
hold on
y2 = cos(2*x);
p2 = plot(x,y2);
y3 = cos(3*x);
p3 = plot(x,y3);
hold off
hf = gcf; % Get Figure Handle
lines = hf.CurrentAxes.Children; % Get °line' Objects From Structure
% lines = findobj(hf, 'Type','line') % Find 'line' Objects (Alternative)
pv = [lines.SeriesIndex]
pv = 1×3
3 2 1
legend([lines(pv(1)) lines(pv(3))], 'First','Third', 'Location','best') % Create 'legend' Object
To remove the legend (or at least make it invisible), use:
legend('off')
I am not certain whether you want to add it or elimiinate it.
Note — The order of the Line objects are reversed in the ‘lines’ array from the way they were originally plotted. The indexing approach makes that easier to work with.
.
  2 Comments
Dmitry T
Dmitry T on 27 Sep 2021
Thanks. That helped. it is easy to adapt this method to combined plots (which have scatter, plot, errorbars)
errorbar = findobj(hf, 'Type','errorbar')
lines = findobj(hf, 'Type','line')
legend([lines(2) errorbar(1)], 'name1','name2')

Sign in to comment.

More Answers (0)

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!