Set data tips programmatically?

不羁岁月 提交于 2019-12-01 10:51:50

You can add matlab datatip programatically and customize them to an extent.

The function below shows how to add a few datatip, position them and customize their display:

The code for this demo (save that in a file demo_datatip.m and run it to obtain the above figure) :

function h = demo_datatip

    %// basic sample curve
    npts = 600 ;
    x = linspace(0,4*pi,npts) ;
    y = sin(x) ;

    %// plot
    h.fig = figure ;
    h.ax = axes ;
    h.plot = plot(x,y) ;

    %// simulate some event times
    time_events = x([25 265 442]) ; %// events type 1 at index 25, 265 and 422

    %// define the target line for the new datatip
    hTarget = handle(h.plot);

    %// Add the datatip array
    h.dtip = add_datatips( time_events , hTarget ) ;


function hdtip = add_datatips( evt_times , hTarget )
    %// retrieve the datacursor manager
    cursorMode = datacursormode(gcf);
    set(cursorMode, 'UpdateFcn',@customDatatipFunction, 'NewDataCursorOnClick',false);

    xdata = get(hTarget,'XData') ;
    ydata = get(hTarget,'YData') ;

    %// add the datatip for each event
    for idt = 1:numel(evt_times)
        hdtip(idt) = cursorMode.createDatatip(hTarget) ;
        set(hdtip(idt), 'MarkerSize',5, 'MarkerFaceColor','none', ...
                  'MarkerEdgeColor','r', 'Marker','o', 'HitTest','off');

        %// move it into the right place
        idx = find( xdata == evt_times(idt) ) ;%// find the index of the corresponding time
        pos = [xdata(idx) , ydata(idx) ,1 ];
        update(hdtip(idt), pos);
    end

function output_txt = customDatatipFunction(~,evt)
    pos = get(evt,'Position');
    idx = get(evt,'DataIndex');
    output_txt = { ...
        '*** !! Event !! ***' , ...
        ['at Time : '  num2str(pos(1),4)] ...
        ['Value: '   , num2str(pos(2),8)] ...
        ['Data index: ',num2str(idx)] ...
                };

If you need to delete a data tip, you can simply call delete(datatip_handle) on it's handle (or even an array of handles to delete them in group).

Here is a small example that might be what you are looking for:

time = 0:0.5:10;
values = rand(1,length(time));
datatip_index = [3 6]; % an 'event' occurs on the 3rd and 6th datapoint 
datatip_text = {'event1', 'event2'};

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