matlabgraphlegendmatlab-figure

How to change line and marker style in a legend?


My script generates a composite plot, made of dozens of lines and line segments. I am trying to add a custom legend to the plot, which contains just 3 of those lines, but I don't seem to be able to control the style of the lines and markers in that legend.

The plot looks like this:

enter image description here

In the legend, I want Line1 style to be 'b.-', Line2 style to be 'r-o' and Line3 style to be 'g-o'.

Is there a way to define a legend with a set number of labels and specific line styles?


Solution

  • You can achieve this using the 'HandleVisibility' property of the plots, which controls whether they appear in the legend or not.

    Since you don't provide an example graph in your code (please do it next time), let's create one:

    t = linspace(0,1,30);
    hold on, grid on
    styles = {'b.-', 'r-o', 'g-o'};
    for k = 1:12
        plot(t, cos(pi/3*t+(k-1)/14*2*pi).*(1-t).^2, styles{mod(k-1,3)+1}, 'linewidth', .8)
    end
    

    Then, all you have to do is:

    set(get(gca, 'children'), 'HandleVisibility', 'off') % existing plots: not in legend
    legend_styles = {'b.-', 'r-o', 'g-o'};
    legend_texts = {'Line1', 'Line2', 'Line3'};
    hold on % make sure existing plots are kept
    for p = 1:numel(legend_styles)
        plot(NaN, legend_styles{p}); % fake plot for legend
    end
    legend(legend_texts{:})
    

    enter image description here