Display name of line in plot

123 ビュー (過去 30 日間)
Alexander Jaksche
Alexander Jaksche 2021 年 5 月 7 日
コメント済み: Alexander Jaksche 2021 年 5 月 16 日
I have a plot with multiple lines and therefore the same color for several lines. Is there a way to display the name of the line when moving over it (to identify it)?
  2 件のコメント
KSSV
KSSV 2021 年 5 月 7 日
Read about legend.
Alexander Jaksche
Alexander Jaksche 2021 年 5 月 7 日
Legend just lists all labels. I want to display the label of the specific line when I move over it with the cursor.

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

回答 (1 件)

Asvin Kumar
Asvin Kumar 2021 年 5 月 10 日
Simple solution
The simplest solution here is to leverage legend. If legend doesn't make sense in your case because all the lines in the plot have the same colour, then I would suggest fixing that since that's easier.
If you're plotting multiple lines using a for loop or a function with some command like this:
plot(x, y, 'r-');
which results in all lines being the same colour, then you can remove the line colour specification. Use this instead:
plot(x, y); % no 'r-'
This results in each line having it's own colour and then the legend will start making sense. It would look like this example. Notice that the line's colour is not specified in both the plot commands in that example.
Another simple approach
However, if you're particular about having the line's name show up in the data tip, that can be done. You will have to customize the data tip and here's an article which shows how that can be done: Create Custom Data Tips
Note that in this example, there exists a third array (statelabel) which contains the custom information for each plotted point. You would have to create such a cell array for each line that you plot.
If you are plotting the i-th line, you could create the cell array for the custom data tip as follows:
%% Plot i-th line
% 1. Get handle of a plotted line
h = plot(x, y, 'r-');
% 2. Convert i to a string and convert that to a cell
lineNum = cellstr(num2str(i));
% 3. Expand cell to as many elements in line
row = dataTipTextRow('Line No', repelem(lineNum,1,numel(x)));
% 4. Add a new data tip row
h.DataTipTemplate.DataTipRows(end+1) = row;
  1 件のコメント
Alexander Jaksche
Alexander Jaksche 2021 年 5 月 16 日
Thank you very much for your answer. I tried the second solution and it works very well.

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

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by