Search code examples
matlabtooltipoverlaymatlab-figuremouseover

How to add tooltips or overlay text in a Matlab figure


I have a figure with two or more lines. These lines have additional, important information associated with them, like how many data points were averaged to create the line etc. I would like to access this information in my figure.

I thought a good solution for this would be to if you could hover over a line with your mouse and get that extended information.

However searching for tooltips/overlays/hover-over on figures seemed to not be fruitful.

Example:

figure; hold on;
plot(1:10,rand(10,1))
plot(1:10,rand(10,1))
% additional info
plot_1_info.name = 'Alice';
plot_2_info.name = 'Bob';
plot_1_info.age = 24;
plot_2_info.age = 12;

Any good solutions or better approaches for this?


Solution

  • Using the new data tip customization system introduced in R2019a, we can do the following:

    figure(); hP = plot(1:10,rand(10,1),1:10,rand(10,1));
    nPts = cellfun(@numel, {hP.XData});
    hP(1).DataTipTemplate.DataTipRows(end+1) = dataTipTextRow('Name', repmat("Alice",nPts(1),1) );
    hP(1).DataTipTemplate.DataTipRows(end+1) = dataTipTextRow('Age',  repmat(12,     nPts(1),1) );
    hP(2).DataTipTemplate.DataTipRows(end+1) = dataTipTextRow('Name', repmat("Bob",  nPts(2),1) );
    hP(2).DataTipTemplate.DataTipRows(end+1) = dataTipTextRow('Age',  repmat(24,     nPts(2),1) );
    % (Of course the above can be organized in a nicer way using a function)
    

    Which yields:

    enter image description here

    Notice that the "hover datatip" has black text, while the "click datatip" has blue text - this is default behavior.