2016-03-24 19 views
1

只是想添加更多的數據做一個圖例而不刪除它。 。Matlab動態圖例/圖例「hold on」like behavior

plotData =陣列繪圖數據,如plotData(I)=圖(...

N =大小plotData的

:像傳說

樣品 「擱置」

代碼

for i = 1:N 
    str = sprintf('My plot y %d', i); 
    %legendData(:,i) = [plotData; str]; %#ok<SAGROW> 
    %[~,~,~,current_entries] = legend; 
    %legend([current_entries [plotData; str]]); no sucess here 

    % This command will erase the previous one. 
    legend(plotData,str); 
end 

legend([plotX1,plotX2],'x 1','x 2'); 

我想我可以存儲從環傳說的信息和某種方式把它添加到最後一行,像:

legend(DATAFROMLOOP?? [plotX1,plotX2],'x 1','x 2'); 

這是一個可能的解決方案,但我不知道該怎麼做。

回答

2

您想要設置您的繪圖對象的DisplayName屬性,然後在完成繪製所有內容時調用legend一次。 legend將自動檢索DisplayName屬性中的字符串以填充圖例。

hplot1 = plot(rand(10,1), 'DisplayName', 'plot1'); 
hplot2 = plot(rand(10,1), 'DisplayName', 'plot2'); 

legend([hplot1, hplot2]); 

enter image description here

您可以輕鬆地集成到一個循環的:

% Create 10 plots within a loop 
N = 10; 

% Pre-allocate graphics objects 
hplots = gobject(N, 1); 

for k = 1:N 
    hplot(k) = plot(rand(10, 1), 'DisplayName', sprintf('My plot y %d', k)); 
end 

legend(hplot); 

enter image description here