MATLAB Answers

Legend has different color lines from plot lines

7 views (last 30 days)
I have the following code to plot some data but the line colors are different from legend's line colors. How I could corrrect it?
for allSS=1:size(scnames,1) ;
nameofsource2open = scnames{allSS,1};
allTCON =[0.3;0.5]
allTECO =[0.2;0.77]
allTENV = [0.56; 0.888]
XallSS2plot = [allTCON(allSS)*0; allTECO(allSS)*(sqrt(3))/2; allTENV(allSS)*(-((sqrt(3))/2));allTCON(allSS)*0]
YallSS2plot = [allTCON(allSS)*1; allTECO(allSS)*(-0.5); allTENV(allSS)*(-0.5);allTCON(allSS)*1]
Xindex2plot = XallSS2plot(:)
Yindex2plot = YallSS2plot(:)
axis , hold on
for i=1:size(scnames,1)
col = rand(i,3)
nameofsource2open = scnames{allSS,1};
hh(i) = plot(XallSS2plot(:,1),YallSS2plot(:,1), 'Color', col(i,:),'LineWidth',2)
legendtext{i} = scnames;
hhh = legend(hh, 'DisplayName',legendtext{i})
linecolors{i} = col(i,:)
legendlinestyles(hhh, {},{},linecolors{i})

Accepted Answer

Geoff Hayes
Geoff Hayes on 10 Oct 2015
Kelly - typically this problem of colour mismatch between what is plotted and what appears in the legend occurs because there are more calls (either explicitly or implicitly) to plot than what you show in the legend. For example see for details.
In your case, I could only get the code to run if I set the scnames variable to a cell array with two rows. (Should this be the case?) Then, two triangles were plotted in blue (larger one) and purple (smaller one inside the other), yet the legend showed the colours as green and blue. Looking closer at your code, you have an inner for loop that does the plotting and this loop iterates over the number of rows in scnames...just like the outer for loop. So your code is calling plot four times drawing four triangles of which only two are distinct. So four colours are used but only two are shown in the legend. You may want to review this to verify whether the above logic is correct and that you do in fact mean to draw four triangles and not just two.
  1 Comment
Kelly Kyriakou
Kelly Kyriakou on 10 Oct 2015
I want 2 triangles not 4, the size of scnames is indeed 2 rows, so my problem is the inner loop as you told!!! Thank you very much for your precious help

Sign in to comment.

More Answers (0)


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!