Pass a plot handle into a function argument

35 ビュー (過去 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
  1 件のコメント
LeChat
LeChat 2023 年 11 月 17 日
This is great thank you.

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeGraphics Object Programming についてさらに検索

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by