What is the Best Way to Deal with an Empty Line Object?
Show older comments
Suppose I have some data:
x = 1:10; y = 1:10;
Now I want to plot three lines based on three logical index vectors.
i1 = x<=3;
i2 = x > 3 & x < 7;
i3 = x >= 7;
hlines = plot(x(i1),y(i1),'r',x(i2),y(i2),'b',x(i3),y(i3),'g');
legend(hlines,'first','second','third');
So far so good. Now suppose i2 is empty
i1 = x<=3;
i2 = x > 100;
i3 = x >= 7;
hlines = plot(x(i1),y(i1),'r',x(i2),y(i2),'b',x(i3),y(i3),'g');
legend(hlines,'first','second','third');
Oops, the legend is not what I want; green should be 'third'.
One way to deal with this is to append NaN to all inputs
hlines = plot([x(i1) nan],[y(i1) nan],'r',[x(i2) nan],[y(i2) nan],'b',[x(i3) nan],[y(i3) nan],'g');
legend(hlines,'first','second','third');
I don't mind that 'second' shows up in legend, even though there is no line. In fact, that's preferred. Keep in mind that all this is in a function and there is no way to know a priori of any of i1, i2, i3 will be empty.
Is there a better way to make sure the the legend is consistent regardless of whether or not i1, i2, or i3 is empty?
Accepted Answer
More Answers (1)
x = 1:10;
y = 1:10;
i1 = x<=3;
i2 = x > 100;
i3 = x >= 7;
hold on
plot(x(i1),y(i1),'r','DisplayName', 'first');
plot(x(i2),y(i2),'b','DisplayName', 'second');
plot(x(i3),y(i3),'g','DisplayName', 'third');
legend show
1 Comment
Walter Roberson
on 13 Jun 2021
This does help, but the user prefers that second also show up, even if there are no visible lines for it.
Categories
Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!




