Legend Title Indexing - Keeps Overwriting
9 views (last 30 days)
Show older comments
Hey!
So I have a plot that has multiple data sets overlaid and I am trying to get the legend to portray the data name for each data set. The tricky part comes from the name of the file, which is imported from a file in a folder path. This is stored as a string variable called "string". The problem I am having is that everytime the for loop runs the legend data name is replaced by the new file name and only displays that line in the legend. I am looking for a method of allowing the legend to index the name of the data set so that it matches what is on the graph and keep them all displayed with the data sets to find errors. The picture attached show my plotting code(circled in red) and the output. Currently there are only 3 files but the eventual goal is to have it scripted so that it can tackle hundreds of files of different types which is why I want to use the file name I pull from the folder without manual input. Is this possible, or is there anyway to format the data to make it possible? 

0 Comments
Answers (2)
Les Beckham
on 23 Feb 2022
One approach that should work is to wait to generate the legend until after the loop is done.
Replace the two lines
stringTmp = strrep(string, '_', '-');
legend(stringTmp)
with this:
legendStrings = {legendStrings; strrrep(string, '_', '-')};
Add this above your for loop to initialize legendStrings as an empty cell array:
legendStrings = {};
Then add this after the end of the for loop:
legend(legendStrings)
0 Comments
Steven Lord
on 24 Feb 2022
Another way to do this is to let each line know what should be added to the legend when you create the line.
When you call plot set the DisplayName property of the line. When you want to display or update the legend, call legend show.
x = 0:360;
axis([0 360 -1 1]);
hold on
for k = 1:4
plot(x, sind(k*x), 'DisplayName', "sin(" + k + "*x)");
end
legend show
0 Comments
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!