matlab plot legend bug

10 views (last 30 days)
mingcheng nie
mingcheng nie on 21 Jan 2023
Answered: Voss on 14 Feb 2023
Hi there, I have no idea what happen to my code about the legend part, it is really weird but I don't know where is wrong.

Answers (1)

Voss on 14 Feb 2023
Some of those plot calls create more than one line so that there's not a 1:1 correspondence between the legend labels you specified and the plot calls.
plot(magic(3)); % plot 3 lines
hold on
plot(1:10,'Color','k'); % plot 1 more line, in black
% now pretend you thought the first plot call would create 1 line only, and
% give two labels to legend:
legend({'line 1','black line'})
xlabel(sprintf('Notice the 2nd label (''black line'') in the legend applies to the red line\nfrom the first plot call and not the black line from the second plot call.'))
Looking at your legend and code, we can say that the first plot call, which creates the dashed blue line, actually created 4 dashed blue lines because there are 4 dashed blue line entries in the legend. Then the second plot call creates one solid blue line. The third plot call creates at least 3 dashed red lines. After that, we don't know how many lines each plot call creates except to say that it's at least one each because there are lines in the axes, but as for exactly how many, we cannot say because the legend entries run out. (It would be easier to go by running the code with your data, but that option is not available unfortunately.) Where are those extra lines, e.g., the three other dashed blue lines created by the first plot call? I don't know. Maybe they coincide with line(s) you can see, or maybe they're all NaNs, or maybe they're off the limits of the axes.
You'll want to make sure those extra plotted lines should really be there, e.g., maybe NMSE1 is a matrix and you expected it to be a vector, etc., but assuming they should be there, how to avoid including those extra lines in the legend? Capture the handles of the lines returned by plot, and use only the first one from each plot call in the legend:
h1 = plot(magic(3)); % plot 3 lines
hold on
h2 = plot(1:10,'Color','k'); % plot 1 more line, in black
% specifying only the two correct lines in legend():
legend([h1(1) h2(1)],{'line 1','black line'})
xlabel(sprintf('Now the ''black line'' legend label applies to the correct line'))
Applying this to your code might look something like this:
lines = []; % array of lines to be used in legend
h = plot(SNR, NMSE); % first plot call (creates 4 lines apparently)
lines(end+1) = h(1); % append only the first plotted line to the lines array
h = plot(SNR, PCRL); % second plot call
lines(end+1) = h(1); % append only the first plotted line to the lines array
% etc., for the remaining plot() calls
% ...
legend(lines,'User1 threshold','User1 PCRB',... % etc., include all your labels





Community Treasure Hunt

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

Start Hunting!