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');

 채택된 답변

Adam Danz
Adam Danz 2019년 6월 3일
편집: Adam Danz 2019년 6월 3일
"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

Outstanding! Thanks, Adam!
Looks like you got two (of the same answer) for the price of one!
Glad I could help.

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

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Annotations에 대해 자세히 알아보기

제품

릴리스

R2019a

질문:

2019년 6월 3일

댓글:

2019년 6월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by