MATLAB Answers

1

turning legend off in xline function

Asked by Manisha RANJAN on 17 Apr 2019
Latest activity Edited by Adam Danz
on 23 Apr 2019
How can I turn off legend of xline function being visible on the plot?

  1 Comment

Can you share a picture?, I don’t see any legend.

Sign in to comment.

Products

2 Answers

Answer by Sean de Wolski
on 19 Apr 2019
Edited by Sean de Wolski
on 19 Apr 2019

myxline = xline(10,'r',"Hello")
myxline.Label = ""
myxline.DisplayName = ""
Disable the label and/or DisplayName.

  3 Comments

You forgot to assign the output
myxline = xline(...)
Also, what does the "Hello" string do? Did you mean this?
xline(10, 'r', 'DisplayName', "Hello")
More importantly, replacing the label and DisplayName with empty strings does not remove that element from the legend.
figure
h = xline(0, 'r', 'DisplayName', 'xline');
h.Label = '';
h.DisplayName = '';
legend() %even if legend is produced before removing label and displayname
190419 100356-Figure 2.jpg
I had myxline = in my command history, apparently failed to copy, doh!
Hello would be the label for the xline, was just showing how you might have the label or not.
In order to create the legend without the xline() don't call legend() directly, call it only on the graphics objects you want:
h = plot(1:10)
xline(3)
legend(h, "Hello World")
I see. "Hello" labels the line on the plot. That's a nice feature.
The legend handel suggestion matches the 'option 1' in my answer, too.

Sign in to comment.


Answer by Adam Danz
on 17 Apr 2019
Edited by Adam Danz
on 23 Apr 2019

Option 1: Use object handles
Specity which objects should appear in the legend and produce the legend at the end after all plotting is complete.
figure
h1 = plot(rand(1,5), rand(1,5));
hold on
h2 = plot(rand(1,5), rand(1,5));
xline(0.5)
legend([h1, h2], {'first', 'second'})
Option 2: Turn off AutoUpdate
If you need to add stuff to the plot after you've created the legend, turn off AutoUpdate before adding the objects.
figure
h1 = plot(rand(1,5), rand(1,5));
hold on
h2 = plot(rand(1,5), rand(1,5));
legend([h1, h2], {'first', 'second'}, 'AutoUpdate', 'off')
xline(0.5)

  0 Comments

Sign in to comment.