问题
Just want to add more data do a legend without erasing it. Like a legend "hold on"
Sample:
plotData
= array of plot data, like plotData(i) = plot(...
N
= size of plotData.
Code:
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');
I think I can store the legend info from the loop and add it some way to the final line, something like:
legend(DATAFROMLOOP?? [plotX1,plotX2],'x 1','x 2');
This is a possible solution, but I don't know how to do it.
回答1:
You want to set the DisplayName property of your plot objects and then call legend
once when you are done plotting everything. legend
will automatically retrieve the strings from the DisplayName
property to populate the legend.
hplot1 = plot(rand(10,1), 'DisplayName', 'plot1');
hplot2 = plot(rand(10,1), 'DisplayName', 'plot2');
legend([hplot1, hplot2]);
You can easily incorporate this into a loop:
% 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);
来源:https://stackoverflow.com/questions/36203272/matlab-dynamic-legend-legend-hold-on-like-behavior