Plot legend contours messed up
이전 댓글 표시
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.
채택된 답변
추가 답변 (1개)
William Rose
2025년 3월 5일
편집: William Rose
2025년 3월 5일
1 개 추천
댓글 수: 6
William Rose
2025년 3월 5일
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
2025년 3월 5일
William Rose
2025년 3월 5일
@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
2025년 3월 5일
Afiq Azaibi
2025년 3월 5일
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
2025년 3월 6일
카테고리
도움말 센터 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!