How can I get the data selected by the user with the datacursor in a Gui?

I have been tryng to create a gui where a user selects a point in a graph. I want to get the user selection to run another function later. I tried to create a function callback in the points in the graph but did not work. How do I create a callback to the graph points?
Thanks.

 Accepted Answer

An example with a line object, save as file and run exampleGUI:
function exampleGUI
lnH(1) = line(1:12,-1:10, 'lines' ,'none', 'marker' ,'.', 'markers',15,...
'markere','k' , 'buttond',@ln_buttond);
% Additional enlarged marker to highlight selected point
lnH(2) = line(1,-1, 'lines' ,'none', 'marker' ,'o',...
'markere','r' , 'markers',8);
function ln_buttond(varargin)
% Retrieve Xdata and Ydata
XY = get(lnH(1),{'Xdata','Ydata'});
% Get mouse position inside axes
cpaxes = get(gca,'currentpoint');
% Index the click
idx = abs(cpaxes(1) - XY{1}) < 0.25;
% Highligth with bigger marker
set(lnH(2),'Ydata',XY{2}(idx),'Xdata',XY{1}(idx));
end
end
Oleg

More Answers (2)

Have you tried the ButtonDownFcn callback?

7 Comments

I did but nothing happens with the callback. When I click the points it doesn't do anything, as if the callback did not exist.
I know, I already wasted 2 days of my life.
Then try Paulo's or my solution below.
My solution doesn't use the datacursor, it just gets the current point when the user clicks on the figure, that was because the datacursor function implements it's own callbacks, I would suggest some alterations to the datacursormode function (make a custom one) but it's not easy.
Maybe adding the detection of the return key or space key in the code
% Parse key press
movedir = [];
switch keypressed
case 'leftarrow'
movedir = 'left';
case 'rightarrow'
movedir = 'right';
case 'uparrow'
movedir = 'up';
case 'downarrow'
movedir = 'down';
case 'alt'
consumekey = true;
end
Make it do something else when those keys are detected but it might not be easy.
I recall that something similar was already discussed and Jiro proposed a solution here on answers, I think I have the code somewhere in my laptop :s
The solution I proposed gets just the point clicked.
Thank you Paulo, Oleg and Aurelien. Paulo and Oleg answers made my day.
Muito Obrigado!

Sign in to comment.

function testbdown
fig=figure;
ax=axes;
set(ax,'ButtonDownFcn',@detbut);
function detbut(a,b)
cp=get(a,'CurrentPoint');
x=cp(1,1)
y=cp(1,2)
%comment the next line if you want to keep getting x,y for more points
set(ax,'ButtonDownFcn','');
%hold on %in case you want to keep several points marked on the axes
%plot(x,y,'x') %in case you want to mark the points
end
end

Categories

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

Community Treasure Hunt

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

Start Hunting!