Legend not showing markers

45 ビュー (過去 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 Center および File ExchangeLegend についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by