How can I make legend by colors?

Hello all,
I have a plot with 4 different colors, the problem is that I don't know in which order the colors are being printed (and it is a bit hard to save the order). Is there anyway to make legend like this:
legend(color1,str_legend1,color2,str_legend2,color3,str_legend3,color4,str_legend4)?
The code:
for kk = 1 : length(vec_ray_angle)
if (shuffling_significance(kk) <= parms.shuffling_significance)
% scatter((ax_bins(kk) - delta),vec_ray_angle(kk), 'g', 'fill'); hold on;
if (sum(kk == idxs_slices_far_from_wall) > 0)
% dark green
vec_color = vec_dark_green;
else
% bright green
vec_color = vec_bright_green;
end
else
% scatter((ax_bins(kk) - delta),vec_ray_angle(kk), 'k', 'fill'); hold on;
if (sum(kk == idxs_slices_far_from_wall) > 0)
% dark blue
vec_color = vec_dark_blue;
else
% bright blue
vec_color = vec_bright_blue;
end
end
plot((ax_bins(kk) - delta),vec_ray_angle(kk), 'color', vec_color); hold on;
text((ax_bins(kk) - delta),vec_ray_angle(kk), num2str(round(vec_ray_angle(kk))), 'color', vec_color);
end
Thanks in advance.

 Accepted Answer

Ced
Ced on 4 Apr 2016
Do I understand correctly that you have a lot of lines, but only want to have 4 legend entries which need to be of different colors?
Why not just generate four dummy points (outside of your figure), one of each color, before the loop? Even nan or inf points would work.
If that doesn't work for you, which version of matlab are you using?
Cheers

5 Comments

Your Idea is not bad, how can I generate 4 dummies outside the figure?
I am using R2011b version, why is it important?
The method of handling legends changed a lot in R2014b and later.
l1 = plot(nan, nan, 'r');
l2 = plot(nan, nan, 'g');
l3 = plot(nan, nan, 'b');
l4 = plot(nan, nan, 'k');
legend([l1, l2, l3, l4], {'legend1', 'legend2', 'legend3', 'legend4'});
All right, I have tried this code:
% plot_dummies for legend
l1 = plot([NaN,NaN], 'color', vec_dark_green);
l2 = plot([NaN,NaN], 'color', vec_bright_green);
l3 = plot([NaN,NaN], 'color', vec_dark_blue);
l4 = plot([NaN,NaN], 'color', vec_bright_blue);
legend([l1, l2, l3, l4], {'significant - far from wall', 'significant - near wall', ...
'not significant - far from wall', 'not significant - near wall'});
But it doesn't show any legend...
"hold on" after the first plot()

Sign in to comment.

More Answers (0)

Asked:

on 4 Apr 2016

Commented:

on 4 Apr 2016

Community Treasure Hunt

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

Start Hunting!