Hi folks,
I found specifying Matlab legend confusing when I have a line that could be empty (then has an empty handle). I want to skip the legend for empty line. For example:
h1 = plot([]); % Blue line
hold on;
h2 = plot(rand(1,10),'r'); % Red line
h3 = plot(rand(1,10),'g'); % Green line
legend([h1 h2 h3],{'want to withdraw this if line unexist', 'hello', 'world'});
In this case, the legend for h1 will be assigned on h2, and the legend for h3 will be ignored.
Do you have any better solution rather than doing (since I might have different lines empty or not, and I just want the matched legends):
h1 = plot([]); % Blue line
hold on;
h2 = plot(rand(1,10),'r'); % Red line
h3 = plot(rand(1,10),'g'); % Green line
if ~isempty(h1)
legend([h1 h2 h3],{'want to skip this if line unexist', 'hello', 'world'})
else
legend([h2 h3],{'hello', 'world'})
end
Thanks!

 採用された回答

Star Strider
Star Strider 2018 年 1 月 10 日

2 投票

Try this:
h1 = plot([], 'DisplayName','want to withdraw this if line unexist'); % Blue line
hold on;
h2 = plot(rand(1,10),'r', 'DisplayName','hello'); % Red line
h3 = plot(rand(1,10),'g', 'DisplayName','world'); % Green line
legend('show')

4 件のコメント

Zheng Liu
Zheng Liu 2018 年 1 月 10 日
Awesome! Thanks!
Star Strider
Star Strider 2018 年 1 月 10 日
As always, my pleasure!
J D
J D 2018 年 11 月 20 日
I had a similar problem, this is perfect! Thanks.
Star Strider
Star Strider 2018 年 11 月 20 日
My pleasure!

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

その他の回答 (0 件)

カテゴリ

質問済み:

2018 年 1 月 10 日

コメント済み:

2018 年 11 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by