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

101 ビュー (過去 30 日間)
Antonio Rubio
Antonio Rubio 2019 年 12 月 23 日
コメント済み: Gelmont Rios 2022 年 7 月 11 日
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!

採用された回答

Adam Danz
Adam Danz 2019 年 12 月 23 日
編集済み: Adam Danz 2020 年 9 月 20 日
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 件のコメント
David Huynh
David Huynh 2022 年 4 月 28 日
This is such an amazing answer, thank you!
Gelmont Rios
Gelmont Rios 2022 年 7 月 11 日
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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeAxis Labels についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by