Search code examples
matlabuser-interfacematlab-guide

Get currently selected data point from axes in a figure


I have a MATLAB figure with an axes containing a scatter plot. Every point on this scatter plot has a signal data array associated with it. I want to take user input as point selection from scatter plot and plot the corresponding signal data in another axes on the same figure.


Solution

  • Combine a global definition of your second axes with an UpdateFcn on the datacursor. See example below, which generates a sine wave based on a random variable selected.

    function getSelectedDataPoint()
    % create figure
    fig = figure;
    % make second axes a global to adress in myupdatefcn
    global ax2
    % define axes
    ax1 = axes('parent',fig,'position',[0.05 0.05 0.9 0.4]);
    ax2 = axes('parent',fig,'position',[0.05 0.55 0.9 0.4]);
    % Random scatter
    scatter(ax1,rand(25,1),rand(25,1),25,'filled')
    % Set datacursormode to on
    dcm_obj = datacursormode(fig);
    datacursormode on
    % Specify objective function for clock
    set(dcm_obj,'UpdateFcn',@myupdatefcn)
    
    % Define objective function
    function text = myupdatefcn(~,obj)
    text = sprintf('X: %f \n Y: %f',[obj.Position(1),obj.Position(2)]);
    % Find corresponding signal
    id = find(and(obj.Position(1) == obj.Target.XData,obj.Position(2) ==             
    obj.Target.YData));
    % Do your thing with the signals
    x = 0:0.1:100;
    y = sin(obj.Target.XData(id)*x);
    % plot on second axes
    plot(ax2,x,y)
    end
    end