MATLAB: How to get the point under mouse click on the plot or histogram

buttondownfcnclickclick bareventhistogramMATLABmouse

I have an axis object in my application, and I am drawing histogram on that axis object.
Is there any event fired when I click a bar on that histogram? If yes How can I intercept that event and get the index of the bar under mouse position?
This is not about the script where I can use 'waitforbuttonpress' this is application where I have nowhere to use any wait function without blocking the application.
Thanks, in Advance.

Best Answer

You can use the ButtonDownFcn function. Here's a demo you can run. It prints the selected bar index to the command window.
figure();
h = histogram(randn(10));
h.ButtonDownFcn = @clickHistFcn;
function clickHistFcn(hObj,event)
% Get the bar edges and click coordinate

edges = hObj.BinEdges;
click = event.IntersectionPoint;
% Determine which bar was clicked

barIdx = find(click(1) >= edges, 1, 'last');
% Do whatever you want with that....
fprintf('bar %d selected.\n',barIdx)
end
Note, this code above does not ignore empty bar bins. For example, try it with these data.
h = histogram([rand(1,20),rand(1,20)+5],10)
If you'd like to ignore empty bars,
function clickHistFcn(hObj,event)
% Get the bar edges and click coordinate
edges = hObj.BinEdges;
values = hObj.Values;
edges([false,values==0]) = []; %remove edges that contain empty bars
click = event.IntersectionPoint;
% Determine which bar was clicked
barIdx = find(click(1) >= edges, 1, 'last');
fprintf('bar %d selected.\n',barIdx)
end