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

조회 수: 38 (최근 30일)
Hakob Bazoyan
Hakob Bazoyan 2019년 8월 18일
편집: Adam Danz 2019년 8월 18일
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
Hakob Bazoyan
Hakob Bazoyan 2019년 8월 18일
Thanks a lot Adam,, this seems to answer my question
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