Plot legend contours messed up
Afficher commentaires plus anciens
I am creating a plot where the data to be plotted is calculated from data in a set of text files. The data is grouped for plotting based on a text string in the filenames. When I add a legend for these groupings ("clumps") the colours in teh legend are messed up.
The script is quite big and messy, so I've created a simpler test script and text files with just two clumps. These are in the attached zip file. The plot created by the test script is this:

Some of the text files don't have all the required data. The script will then try to plot [NaN NaN] for those files.
The legend is not messed up if I remove these text files. In the files provided, delete the first two "Scar" files and you get this:

Where am I going wrong?
UNfortunately, I cannot change the approach of constructing the plot from the text files. The text files are generated by other software and there can be several hundred of them, in up to 12 clumps.
Réponse acceptée
Plus de réponses (1)
William Rose
le 5 Mar 2025
Modifié(e) : William Rose
le 5 Mar 2025
1 vote
6 commentaires
William Rose
le 5 Mar 2025
Thanks for posting a simplified version of your script, to make it easier for others to assist you. It would be great if more people on this site followed your good example.
dormant
le 5 Mar 2025
William Rose
le 5 Mar 2025
@dormant, good luck.
I edited my earlier answer, by updating the script. My first script used
legend( pHandle(legPlot), 'location', 'northeast' );
and the new version uses
legend( pHandle(legPlot), legendItems, 'location', 'northeast' );
The original script which you posted uses
legend( legendItems, 'location', 'northeast' );
where legendItems is a cell array containing two strings. When legend() sees this, it uses the two strings, and it uses the symbol and color info for the first two data sets in the plot. But what we want, in this case, are the symbol and color info for set 1 and set 4, since sets 1 and 4 correspond to clump 1 and clump 2. Therefore I searched Matlab Answers for "how to change the legend order" and I found an answer here - thank you, @Afiq Azaibi. (@Afiq Azaibi gives three ways to do it; I used method 1.) I could also have read the help for legend() and noticed the optional argument "subset".
dormant
le 5 Mar 2025
Afiq Azaibi
le 5 Mar 2025
To echo the relevant information from that post, if you want certian objects to appear in a legend in a certain order, the best practice is to speicfy the objects in the legend() command. This syntax is referenced as subset in the doc and is what the William points out as my first method.
dormant
le 6 Mar 2025
Catégories
En savoir plus sur Legend dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!