MATLAB: How to make the legend visible only when the cursor is near the bottom left of the figure in MATLAB 7.12 (R2011a)

invisiblelegendMATLAB

I have a scatter plot with about 14 different colors/patterns. Rather than leaving the legend permanently visible, where it would take up a lot of needed space, I would like to explain the colors in a more discreet fashion by either making the legend invisible unless one rolls a cursor over the lower left hand side of the figure.

Best Answer

In order to implement this, you need to do the following:
1. Create a callback function that gets triggered when the mouse moves. The 'WindowButtonMotionFcn' function does this.
2. Inside the callback, you could turn the legend on or off based on the current cursor position. The current cursor position can be queried using the 'CurrentPoint' property. Based on the current point, you can turn the legend off using: legend('off').
The following example illustrates this. The main function is shown below. It creates a scatter plot and sets the a callback for 'WindowButtonMotionFcn'.
% Example code creating a scatter plot in which legend is visible only when
% cursor is near bottom left of the axes.
% create scatter plot
scatter(rand(1,50),rand(1,50));
hold on;
scatter(rand(1,50),rand(1,50),'r');
% set mouse motion callback to mouseMove
set(gcf,'WindowButtonMotionFcn',@mouseMove);
The callback function is as follows:
function mouseMove (object, eventdata)
% callback function that makes legend visible when cursor is in the bottom
% left of the axes.
% get location of current point
C = get (gca, 'CurrentPoint');
title(gca, ['(X,Y) = (', num2str(C(1,1)), ', ',num2str(C(1,2)), ')']);
% test if current point is in the bottom left of the axes.
if C(1,1) < 0.2 && C(1,2) < 0.2
% display legend
legend('a','b');
else
% turn legend OFF
legend('off');
end
You can find a list of properties and callbacks that can be used to manipulate figures at the following location:
The LEGEND function and its various syntaxes are located at the following link for your perusal: