Pass a plot handle into a function argument

조회 수: 32 (최근 30일)
LeChat
LeChat 2023년 11월 16일
댓글: LeChat 2023년 11월 17일
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