Pass a plot handle into a function argument

33 次查看(过去 30 天)
Hi, I would like to write a function to easily remove the plot I just created from the figure legend.
Say I call the plot plt such as:
figure(1)
xx=linspace(-pi,pi,100);
yy=sin(xx);
plot(xx,yy,'r-','DisplayName','sinus')
% then plot a second curve which I do NOT want in the legend
plt=plot(xx,yy-2,'b--');
I was thinking of writing a function skiplegend(plt) right after this line to remove it from the legend, instead of having to write :
set(get(get(plt,'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
Here is the code of the function I wrote:
function skipleg=skiplegend(varargin)
plt=varargin{1};
scriptline1=['set(get(get('];
scriptline2=[',''Annotation''),''LegendInformation''),''IconDisplayStyle'',''off'');'];
scriptline=[scriptline1,plt,scriptline2];
skipleg=eval(scriptline);
end
But it seems I do not manage to handle a plot and use it as an argument in a function. Here is the error I get :
>> skiplegend(plt)
Error using get
Invalid handle
Error in skiplegend (line 6)
skipleg=eval(scriptline);
Any idea on how I should proceed? Thank you for your help!

采纳的回答

Fangjun Jiang
Fangjun Jiang 2023-11-16
figure(1)
xx=linspace(-pi,pi,100);
yy=sin(xx);
plot(xx,yy,'r-','DisplayName','sinus');
legend;
hold on;
% then plot a second curve which I do NOT want in the legend
plt=plot(xx,yy-2,'b--');
Showlegend(plt,'off');
function Showlegend(plt,OnOff)
set(get(get(plt,'Annotation'),'LegendInformation'),'IconDisplayStyle',OnOff);
end

更多回答(2 个)

Voss
Voss 2023-11-16
You can use 'HandleVisibility','off' to prevent lines from showing up in the legend.
figure(1)
hold on
xx=linspace(-pi,pi,100);
yy=sin(xx);
plot(xx,yy,'r-','DisplayName','sinus')
% then plot a second curve which I do NOT want in the legend
plt=plot(xx,yy-2,'b--','HandleVisibility','off');
legend

Steven Lord
Steven Lord 2023-11-16
Another way to control what is or is not included in the legend, if you have (through calling plot with an output argument) or can find (using findobj or findall) the handles to the items you want to include / exclude from the legend, is to pass a vector of graphics handles to the legend function.
% Sample data
x = 0:360;
% Set axes limits to something that shows all three plots "nicely"
axis([0 360 -5 5])
hold on
grid on
% Store the handles to the three plots
h = gobjects(1, 3);
h(1) = plot(x, sind(x), 'DisplayName', 'sine');
h(2) = plot(x, cosd(x), 'DisplayName', 'cosine');
h(3) = plot(x, tand(x), 'DisplayName', 'tangent');
% Show only sine and tangent in the legend
legend(h([1 3]))

类别

Help CenterFile Exchange 中查找有关 Graphics Object Programming 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by