Search code examples
matlabcallbackmatlab-figureaxes

Mouse click callback in MATLAB for line plot


If I want to read location of the mose click on some image I can do it using callback action.

function[]=FooBar
Img=imshow(FooMatrix,'callback',@(s,e)ImageClickCallback());

 function ImageClickCallback(objectHandle,~)
  axesHandle  = get(objectHandle,'Parent');
  coordinates = get(axesHandle,'CurrentPoint');
  coordinates = round(coordinates(1,1:2))
 end
end

It works well for images but now I have axes with lines only. I tried to set the callback routine to the appropriate axes or the line but I got the error message

Error while evaluating uicontrol Callback

Error using hg.figure/set The name 'callback' is not an accessible property for an instance of class 'figure'.


Background:
I am trying to create GUI with line plot, say y=f(x) enabling user to select points on the line. Idea is to read the [x,y] coordinates of the mouse click and highlight the point [f'(y),y] or [x,f(x)], where f' is inverse function to f. Something like Data Cursor function does.


Solution

  • callback isn't a valid property of a line object. You'll want to set the ButtonDownFcn property of the line object.

    h = plot(1:3, 'ButtonDownFcn', @(s,e)ImageClickCallback()
    

    The ButtonDownFcn property is also available for most of UI elements (including axes)

    set(gca, 'ButtonDownFcn', @mycallback)