The order of plotted things vs the order of the legend

5 次查看(过去 30 天)
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by