2017-02-26 129 views
4

MATLAB图例列出了图中的所有内容,包括您已将图放置在图上的指南。隐藏图中某些图形对象的MATLAB图例条目

在敷衍绕过那就是做

*Plot 
*Add legend 
*Add guidelines 

然而,MATLAB把最近的线在前面,意思是指引然后再坐在显示的数据;丑陋和分散注意力。

类似的问题在任何时候发生,你建立一个复杂的情节,legend怪胎出来,抓住一切,并密谋为了解决方法可以丑

示例代码:

%**** Optional guidelines 
figure(1) 
plot([2 2],[0,1],'k--'); hold on 

%**** DATA 
N = 4; 
y=rand(5,N); 
x=1:1:5; 
for plotLoop=1:N; 
    %* Plot 
    figure(1) 
    plot(x,y(plotLoop,:)); 
    hold on 
end 

%*****LEGEND 
hLegend = legend(LegTxt,... 
       'interpreter','latex',... 
       'location','eastoutside') 

(移动代码块为了复制上述情况)

如何合理地解决这个问题?

+0

我已经更新了标题,以使它有点更一般 - 它可能不仅仅是指导方针,而是例如粗线条或类似物,您不想显示为图例条目 – Jonas

回答

6

如果你想有一个特定的图形对象,以不产生传说(如果您切换的传说,然后再打开这甚至会工作),你可以修改LegendInformation

%# plot something that shouldn't show up as legend 
handleWithoutLegend = plot(something); 

%# modify the LegendInformation of the Annotation-Property of the graphical object 
set(get(get(handleWithoutLegend,'Annotation'),'LegendInformation'),... 
    'IconDisplayStyle','off'); 

%# toggle legend on and off at will, and never see the something-object appear 

如果您尝试关闭图例句柄的数组上,最好的办法就是循环他们,用一个try-包装的图形对象不能产生一个传说:

for h = listOfHandles(:)' 
    try 
     set(get(get(h,'Annotation'),'LegendInformation'),... 
     'IconDisplayStyle','off'); 
    end 
end 
+1

我建议把这个命令放到一个函数“noLegend”之类的东西里,因为我真的不能记住它。 – Jonas

+0

我尝试使用代码,并得到错误'从单元格转换为double是不可能的.'' get(bla,'LegendInformation')'。你知道为什么吗?我认为代码只适用于一些图形对象,而不是全部? –

+0

@Mark_Anderson:我现在添加了一个可以解决您的问题的循环解决方案。 – Jonas

3

制作一个自定义手柄,将其送入legend。绘图手柄可以连接起来形成图例很高兴接受为输入的对象。

所需的代码并不漂亮,但它确实有效。

%**** Optional guidelines for periodicity 
figure(1) 
plot([2 2],[0,1],'k--'); hold on 

%**** DATA 
N = 4; 
y=rand(5,N); 
x=1:1:5; 

for plotLoop=1:N; 
    LegTxt{plotLoop} = num2str(plotLoop); 
    %* Plot 
    figure(1) 

    % if statement to construct a handle for the legend later 
    if plotLoop==1 
     htot=plot(x,y(plotLoop,:)); 
    else 
     h=plot(x,y(plotLoop,:)); 
     % Append this info to the figure handle 
     htot= [htot, h]; 
    end 
    hold on 

end 

%*****LEGEND 
hLegend = legend(htot,LegTxt,... 
       'interpreter','latex','FontSize',16,... 
       'location','eastoutside') 

对于迂腐或好奇,环路for plotLoop=1:N;是在这里,因为我从一些相当复杂的代码,其中所述数据是从单元阵列中提取提取的例子。显然你可以在很多使用场景中消除这个循环,我只是决定保持代码的最灵活的格式!

+0

此方法可行,但如果您手动关闭图例然后重新打开,则不需要的项目仍会出现。幸运的是,还有另一种解决方案:http://stackoverflow.com/a/42471561/232610 – Jonas

+0

够公平的,我从来没有在MATLAB中使用手动绘图交互工具,所以我没有遇到问题! –