Reputation: 399
There are 30 lines on this plot and each line corresponds to a particular object. Now I want to display all the object's name. But I don't want a messy legend with 30 entries.
What I want is to be able to hover the cursor over any line (or use the data cursor) and then it object's name should appear.
Is that possible to do in Matlab. Thanks!
Upvotes: 1
Views: 227
Reputation: 125864
Implementing text that appears when hovering over an object is doable, but can be quite involved. It would require setting a WindowButtonMotionFcn
callback for your figure which would continuously check the CurrentPoint
property of the figure to determine if it was within your axes of interest, and if so then check the CurrentPoint
property of that axes and compute which child plot object is the closest.
If you're willing to allow the user to click and not just hover for text to appear, that's much simpler. You could set the ButtonDownFcn
callback of each plotted line to display text in a given location. Here's an example that creates two line objects and assigns them a callback function that will display the Tag
of the line that is clicked on at the cursor point:
function line_click_example
hAxes = axes('NextPlot', 'add', 'ButtonDownFcn', @clear_text);
hLines = line(hAxes, [1:10; 1:10].', [rand(10, 1) rand(10, 1)+1]);
set(hLines, 'ButtonDownFcn', @line_click_fcn, ...
'Tag', {'Line 1'; 'Line 2'});
hText = text(hAxes, 0, 0, '');
function line_click_fcn(hSource, ~)
cursorPosition = get(get(hSource, 'Parent'), 'CurrentPoint');
set(hText, 'Position', cursorPosition(1, [1 2]), ...
'String', get(hSource, 'Tag'));
end
function clear_text(~, ~)
set(hText, 'Position', [0 0], 'String', '');
end
end
Here, I've also set the ButtonDownFcn
of the axes so that it will clear the text object, meaning that clicking on any region of the axes that isn't over one of the two lines will remove the displayed text. Notice also that, since line_click_fcn
and clear_text
are nested functions, they will both have access to hText
and be able to modify it.
Upvotes: 1