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

104 vues (au cours des 30 derniers jours)
Antonio Rubio
Antonio Rubio le 23 Déc 2019
Commenté : Gelmont Rios le 11 Juil 2022
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!

Réponse acceptée

Adam Danz
Adam Danz le 23 Déc 2019
Modifié(e) : Adam Danz le 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
  2 commentaires
David Huynh
David Huynh le 28 Avr 2022
This is such an amazing answer, thank you!
Gelmont Rios
Gelmont Rios le 11 Juil 2022
FYI: I found it was easy to plot a large matrix first and set the legend and then do this code
z=rand(10,10);
leg=repmat({'z'},10,1);
leg=genvarname(leg)
h=plot(z);
legend(leg)
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
% this is optional if you dont want legend to display
legend off

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by