MATLAB Answers

0

Legend not showing markers

Asked by Seth Martin on 15 Feb 2018
Latest activity Answered by Kelly Kearney
on 19 Feb 2018
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.

  0 Comments

Sign in to comment.

2 Answers

Answer by Kelly Kearney
on 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.

  0 Comments

Sign in to comment.


Answer by Seth Martin on 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.

  0 Comments

Sign in to comment.