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

37 ビュー (過去 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 Center および File ExchangeGraphics Object Programming についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by