Legend not showing markers

조회 수: 48 (최근 30일)
Seth Martin
Seth Martin 2018년 2월 15일
댓글: Mary Zeller 2020년 8월 20일
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.

답변 (2개)

Kelly Kearney
Kelly Kearney 2018년 2월 19일
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
Mary Zeller
Mary Zeller 2020년 8월 20일
Thanks, this worked great for me!

댓글을 달려면 로그인하십시오.


Seth Martin
Seth Martin 2018년 2월 19일
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.

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by