Search code examples
matlablegendmatlab-figurematlab-hg2

Custom Legend Matlab 2014b


I have a figure where I had some plots trough different functions using hold on.

When I want to create my Legend, I don't have access to all the handle of my figures.

Is there a way to create an independent Legend by defining the tip of the plot and the string for the description?

For example I would like to be able to do:

figure;
plot(0:0.1:pi, sin(0:0.1:pi), 'b-');
customLegend('r.', 'red dots');

In the previous version it was possible to create a virtual plot using:

h1 = plot([], [], 'r.');
legend(h1, 'red dots');

For example I want to change from the image of the left to the image of the right:

enter image description here


Solution

  • Just use NaN instead of []:

    figure;
    plot([1:20], [-9:10], 'b-');
    hold on
    h1 = plot(NaN, NaN, 'r.');
    legend(h1, 'red dots');
    

    enter image description here

    My interpretation of why this works: using NaN generates a line object h1 (size 1x1). This line is not visible in the figure because NaN values are not shown in graphs, but you can use it for the legend. On the contrary, using [] produces an empty h1 (size 0x1), which doesn't have the desired effect when used as the first input of legend.