R.Falque
R.Falque

Reputation: 944

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

Upvotes: 1

Views: 2709

Answers (2)

R.Falque
R.Falque

Reputation: 944

So I got this solution which is not very elegant (plotting outside of the window, save the handle and resizing the window to the original axis).

figure;
plot(0:0.1:pi, sin(0:0.1:pi), 'b-');

hold on;
a = axis; 
h1 = plot(min(a) - 10, min(a),  'r.'); % plots outside of the current figure
axis(a);
legend(h1, 'red dots');
hold off;

If someone has a more elegant solution, I would be happy to take it :)

Edit: it is actually possible to use a nan instead of [] like:

h1 = plot(nan, nan, 'r.');
h2 = plot(nan, nan, 'b+');
legend([h1, h2], 'red dots', 'blue cross');

However this method does not work with the rectangles command.

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112669

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.

Upvotes: 3

Related Questions