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

时光毁灭记忆、已成空白 提交于 2019-11-29 12:37:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!