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

23 views (last 30 days)
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.

Accepted Answer

Adam Danz
Adam Danz on 18 Aug 2019
Edited: Adam Danz on 18 Aug 2019
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
  2 Comments
Adam Danz
Adam Danz on 18 Aug 2019
Great! If you plan to return information about the bar plot, you can get that info from the 'hObj' handle which is the first input to the buttondown function.

Sign in to comment.

More Answers (0)

Categories

Find more on Graphics Object Programming in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!