MATLAB scatter with tooltip showing other kinds of data and connecting points with arrowhead

前端 未结 1 1331
一整个雨季
一整个雨季 2020-12-20 07:29

I want to ask two questions here. In short they are,

  1. In a scatter plot in MATLAB how can I click a point using the tooltip and get not the x,y data but some

相关标签:
1条回答
  • 2020-12-20 08:05

    Answer 1

    One solution is you define your own callback function for the data-tooltip. To do that, you first need to save Names within the figure. We can use UserData property for that:

    % modify the end of your code to:
    gsh = gscatter(xData',yData',group');
    Names = [LionNames WolfNames];
    set(gsh,{'UserData'},{Names});
    

    Next, we create the following callback function (I took Matlab's defualt and edit it), and save it in new m-file:

    function output_txt = tooltip_callback(obj,event_obj)
    % Display the position of the data cursor
    % obj          Currently not used (empty)
    % event_obj    Handle to event object
    % output_txt   Data cursor text string (string or cell array of strings).
    
    pos = get(event_obj,'Position');
    output_txt = {['X: ',num2str(pos(1),4)],...
        ['Y: ',num2str(pos(2),4)],...
        event_obj.Target.UserData{event_obj.Target.XData==pos(1)}}; % <- this line is the only change
    % If there is a Z-coordinate in the position, display it as well
    if length(pos) > 2
        output_txt{end+1} = ['Z: ',num2str(pos(3),4)];
    end
    

    Now we click on one of the tooltips in the figure and choose Select Text Update Function:

    and from the browser we pick the callback function we saved.

    The result:

    In the same manner, you can add the days to the tooltip if you want, or use my answer to Q2...

    Answer 2

    Here is how you can use annotations to do that:

    ax = axes;  % create the axis
    % plot all lines (no need for the loop) so we can put the legend after:
    p = plot(day1Lions,day2Lions,'-');
    legend('Tyrion','Jamie','Cersei')
    % get the lines colors:
    col = cell2mat(get(p,'Color'));
    % loop through the arrows:
    for k = 1:size(day1Lions, 2)
        % get the data coordinates:
        x = day1Lions(:,k);
        y = day2Lions(:,k);
        pos = ax.Position;
        % convert them to normalized coordinates:    
        %  white area * ((value - axis min)  / axis length)  + gray area
        normx = pos(3)*((x-ax.XLim(1))./range(ax.XLim))+ pos(1);
        normy = pos(4)*((y-ax.YLim(1))./range(ax.YLim))+ pos(2);
        % plot the arrow
        annotation('arrow',normx,normy,'Color',col(k,:))
    end
    

    the result:

    you could also set the original lines invisable, with:

    set(p,{'Visible'},{'off'})
    

    but it will turn the legend text gray, and they are totally covered by the arrows anyway.

    0 讨论(0)
提交回复
热议问题