MATLAB Answers

Displaying the name of a trace in plot() in a data tip

60 views (last 30 days)
Antonio Rubio
Antonio Rubio on 23 Dec 2019
Edited: Adam Danz on 20 Sep 2020
I'm using MATLAB R2019a. I have a plot with many different traces and would like to display the name of the trace along with the X and Y coordinates. I found one solution that displays the name but in the command window. Another one that allows you to modify the data tip. However I cant figure out how to get the data tip to display the name of the trace. Right now the only way to know is if I create a legend. The problem is there are a lot of traces and the colors repeat. Is there anyway I can display the name of the trace (which I define in legend()), x and y coordinates on the data tip?
Thank you!

Answers (1)

Adam Danz
Adam Danz on 23 Dec 2019
Edited: Adam Danz on 20 Sep 2020
Use dataTipTextRow(label,value) to add a new row to the datatip of each line object. The best way to organize this is to assign a DisplayName to the line objects that would appear in the legend (if one exists) and will be used in the DataTip. There needs to be one label for each coordinate within the line so the DisplayName value can be replicated using repmat().
Here's a demo.
clf()
hold on
h(1) = plot(rand(1,20),'-o','DisplayName','A');
h(2) = plot(rand(1,20),'-o','DisplayName','B');
h(3) = plot(rand(1,20),'-o','DisplayName','C');
h(4) = plot(rand(1,20),'-o','DisplayName','D');
h(5) = plot(rand(1,20),'-o','DisplayName','E');
for i = 1:numel(h)
% Add a new row to DataTip showing the DisplayName of the line
h(i).DataTipTemplate.DataTipRows(end+1) = dataTipTextRow('Trace',repmat({h(i).DisplayName},size(h(i).XData)));
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!