MATLAB: How to identify which bar is clicked in a BAR plot

MATLAB

I want be able to click on a bar of the histogram and identify which bar was clicked.

Best Answer

The ability to do this in MATLAB is not available. However it is possible to write MATLAB code that allows expected behaviour.
The code uses the "ButtonDownFcn" to detect the mouse click. Once the mouse is clicked the function "mouse_fcn" is invoked. This function computes the bar which is selected based on the mouse position and returns a logical vektor that indicates which bar was selected.
h = bar(rand(1,5));
barclick(h)
You can use this to then execute your own custom function. Please note that the code will need modification in case if you have a bar groups.
function barclick(hbar)
xd = get(get(hbar,'children'),'XData');
yd = get(get(hbar,'children'),'YData');
set(gcf,'WindowButtonDownFcn',{@mouse_fcn,xd,yd});
function mouse_fcn(h,cnc,xd,yd)
cp = get(gca,'CurrentPoint');
id = and(~sign(sum(sign(cp(1)-xd(2:3,:)))),~sign(sum(sign(cp(3)-yd(1:2,:)))))