MATLAB: Creating a legend that is unrelated to the plotted data

image processinglegend

Hello!
For some context, I am currently writing a code which identifies two different types of objects in an image. Ultimately I am comparing the locations for the second type of object (the smaller objects) to the border of the first (larger objects). I have created a figure which takes the original image, draws on the borders of the large objects, and draws the small objects on in another color. I have then marked the smaller objects with a color code, where the small objects that lie within a larger object are color 1, the small objects lying on the perimeter of a larger object are color 2, and the ones outside the larger objects are color 3. I then have a multitude of lines plotted from each small object to the larger objects, all in one of the three colors. I would like to add a legend which simply designates what type of relationship each color represents, so "color 1 = inside, color 2 = perimeter, color 3 = outside". The problem is that when I add the legend, it wants to make a separate entry for each individual line in the plot. Is there any way to simply add a legend that describes the meaning of each color, without having a direct relationship to the individual lines on the image?

Best Answer

The way to create legends that do not depend upon what you drew, is to create additional graphics objects with positions that are not finite (that use, use inf or nan) and record their handles, and legend() passing in those handles.
L1 = plot(nan, nan, 'color', first_color);
L2 = plot(nan, nan, 'color', second_color);
L3 = plot(nan, nan, 'color', third_color);
legend([L1, L2, L3], {'inside', 'perimiter','outside'})