The order of plotted things vs the order of the legend

5 views (last 30 days)
I'm using patch to show a confidence interval in a matlab plot as a colored region. Assume vectors of time values, tv, and mean values, mvs, and standard error of means, sems. I can use
figure('Name','Confidence Intervals');
patch( [ tv; flipud(tv)] , [mvs-sems; flipud(mvs+sems)] ,'g','EdgeColor','g');
hold on
I have to plot the colored interval first (I think) so that when I plot the mean value
plot(tv,sems, 'k-' );
The line shows up on top of the interval. If I plot the line first, the colored "patch" region covers it. But if I add a legend, I have to use
legend('Mean +/- One SEM', 'Mean');
So the legend order is dictated by the order of plotting, that is, first mean +/- interval then the mean. I'd prefer if I could have the legend order be mean then interval. The displayed legend uses the actual patch or line color to indicate association, so there's no reason for it to force order. Is there a way that I can change the order of the legend without affecting the plot order?
A working script may be useful for some folks (keep in mind this is illustrative, not mathematically/statistically rigorous!)
% patch_interval.m
tv = (0:0.25:10)';
ntv = numel(tv);
alls = randn(ntv,10);
sv = mean(alls,2);
semv = std(alls,0,2)/sqrt(ntv);
figure('Name','Legend Order');
patch([tv; flipud(tv)],[sv-semv; flipud(sv+semv)],'g','EdgeColor','g');
hold on;
plot(tv,sv);
ylim([-1 1.2]);
legend('Confidence Interval','Mean', 'location','northeast');

Accepted Answer

Adam Danz
Adam Danz on 3 Jun 2019
Edited: Adam Danz on 3 Jun 2019
"Is there a way that I can change the order of the legend without affecting the plot order"
Yes. Use object handles to specify the order when you call legend().
tv = (0:0.25:10)';
ntv = numel(tv);
alls = randn(ntv,10);
sv = mean(alls,2);
semv = std(alls,0,2)/sqrt(ntv);
figure('Name','Legend Order');
patchHand = patch([tv; flipud(tv)],[sv-semv; flipud(sv+semv)],'g','EdgeColor','g'); %store handle
hold on;
plotHand = plot(tv,sv); %store handle
ylim([-1 1.2]);
legend([plotHand, patchHand], {'Mean','Confidence Interval'}, 'location','northeast'); %specify order
  2 Comments
Adam Danz
Adam Danz on 3 Jun 2019
Looks like you got two (of the same answer) for the price of one!
Glad I could help.

Sign in to comment.

More Answers (0)

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!