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

32 次查看(过去 30 天)
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.

采纳的回答

Adam Danz
Adam Danz 2019-8-18
编辑:Adam Danz 2019-8-18
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 个评论
Adam Danz
Adam Danz 2019-8-18
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Graphics Object Programming 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by