Plotting legends in loop for mean and standard deviation of spectra

4 次查看(过去 30 天)
I have mean values for my spectra and their standard deviation saved as
meanC=mean(C)
stdC=std(C)
the labels for my C data are saved as labelC
wavenumbers1 is the x axis of my data.
I wand to plot the mean spectra(meanC) vs wavenumbers and I want each spectrum to have a legend. I also want to plot the meanC+std and meanC-std as a shaded area around each mean. But I want to get the legend of the standard deviation curve only one time since it's the same color for all means. How should I go about this?
at the moment since I am using a loop, I get half of the legends of the mean spectra in my plot.... should I turn off the legends for the standard deviation? how would I do that using patch?
I am open to doing this with other functions if it's more efficient that way! I'm using Matlab R2018a
Thank you!
for i=1:M;
plot(wavenumbers1,(meanC(i,:)); legend(labelC)
hold on
patch([wavenumbers1' fliplr(wavenumbers1')], [((meanC(i,:))+stdC(i,:)) fliplr((meanC(i,:))-stdC(i,:))], 'r', 'FaceAlpha',0.5, 'EdgeColor','none')
end

采纳的回答

Matt Gaidica
Matt Gaidica 2021-1-15
I think what you want to do is utilize the subset input for legend. What I usually do is something like this:
lns = [];
for i=1:M
lns(i) = plot(wavenumbers1,(meanC(i,:));
hold on;
% plot other stuff
end
legend(lns,{"Label1", "Label2", "LabelM"});
  2 个评论
ardeshir moinian
ardeshir moinian 2021-1-15
That is great! It worked as follows.
I want to show the legend for standard deviation as well (just once since it's the same color for all spectra). I did this:
for i=1:M;
lns(i)=plot(wavenumbers1,(meanC(i,:)+i*30000));legend(legends(i));hold on
hold on
ptc(i)=patch([wavenumbers1' fliplr(wavenumbers1')], [((meanC(i,:)+i*30000)+stdC(i,:)) fliplr((meanC(i,:)+i*30000)-stdC(i,:))], 'r', 'FaceAlpha',0.5, 'EdgeColor','none')
end
legend(lns,legends);
legend(ptc,{'Standard Deviation'})
but I get this:
I guess the 2nd legend overrides the first one for "lns" but I want to keep both and I don't know how.
Thank you in advance!
Matt Gaidica
Matt Gaidica 2021-1-15
Do this:
for i=1:M;
lns(i)=plot(wavenumbers1,(meanC(i,:)+i*30000));
hold on
lns(M+1)=patch([wavenumbers1' fliplr(wavenumbers1')], [((meanC(i,:)+i*30000)+stdC(i,:)) fliplr((meanC(i,:)+i*30000)-stdC(i,:))], 'r', 'FaceAlpha',0.5, 'EdgeColor','none')
end
legend(lns,{legends{:},'Standard Deviation'});

请先登录,再进行评论。

更多回答(0 个)

类别

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

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by