Legend not showing markers

22 Ansichten (letzte 30 Tage)
Seth Martin
Seth Martin am 15 Feb. 2018
Kommentiert: Mary Zeller am 20 Aug. 2020
I have a figure with a plot and an inset. I want a shared legend for the main plot and the inset axes. The following code creates the effect I want, except that the legend entries that correspond to the data in the inset figure only show errorbars in the plot, not the markers.
figure; hold on
data1 = [0. .5 1. 2. 4. 16.];
data2 = [0. .2 1.5 2.2 3.5 15.];
error = [0.5 .6 .7 .8 .9 1.];
aa = gca;
f1 = errorbar(data1,error,'ok','MarkerFaceColor','k')
f2 = fplot(@(x) x^2, [0. 6.], 'k-')
bb = axes('Position',[.2 .5 .3 .3]); hold on
f3 = errorbar(data1,error,'or','MarkerFaceColor','k')
f4 = errorbar(data2,error,'^b','MarkerFaceColor','k')
box on
legend(aa,[f1 f2 f3 f4],{'data1A','fplot','data1B','data2'},'Location','southeast')
Any ideas on what's causing this, or how to fix it? Alternatively another approach that gives the same desired result is fine.

Antworten (2)

Kelly Kearney
Kelly Kearney am 19 Feb. 2018
I've found that legends can sometimes benefit from taking a deep breath. Not sure exactly why, but it seems that since the introduction of HG2 (R2016b), legends sometimes start to do their analysis of the labeled objects before those objects are fully rendered, and therefore they can miss some details. I've never taken the time to really dig into this bug, because the solution is pretty straightforward: add a pause. I added the following to your code:
pause(0.1);
legend(aa, [f1 f2 f3 f4],{'data1A','fplot','data1B','data2'},'Location','southeast')
Without the pause, I get the bar-and-whiskers legend markers only. With the small pause, the markers suddenly appear correctly.
  1 Kommentar
Mary Zeller
Mary Zeller am 20 Aug. 2020
Thanks, this worked great for me!

Melden Sie sich an, um zu kommentieren.


Seth Martin
Seth Martin am 19 Feb. 2018
So I found a work around which works, if inelegantly. In the figure axes (aa), I plot the same errorbar calls, but with nan arguments in place of my data. I can then use the nan errorbar calls to generate my legend, rather than those in axes bb.
I do feel that the behavior I described in the question should be achievable without unnecessary plotting calls though.

Community Treasure Hunt

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

Start Hunting!

Translated by