MATLAB: How to add a legend to a plot with multiple data sets and 3 curves per data set

legendplot

Hello,
I'm trying to add a legend to a battery discharge plot. For each battery, there are three curves on the plot (voltage 1, voltage 2, and resistance). All three curves are the same color for each battery. There may be up to 20 batteries on each plot (60 total curves).
How can I create a legend that labels the color for each battery? I'd want 20 total labels if there were 20 batteries in the figure.
Here is my code:
for file = files'
[capacity1{i}, bgCurve1{i}, pulseCurve1{i}, resCurve1{i}] = getDischargeCurves(fileDir, file.name);
fnames{i} = file.name
plot(capacity1{i}, bgCurve1{i}, 'color', colors(i,:))
set(gca, 'xlim', [0 .5])
set(gca,'ylim',[2 3.3])
set(gca,'xtick',[])
set(gca,'ytick',[])
[AX,H1,H2]=plotyy(capacity1{i}, pulseCurve1{i}, capacity1{i}, resCurve1{i}) ;
set(AX(:), 'xlim', [0 .5])
set(AX(1), 'ylim', [2 3.3])
set(AX(2), 'ylim', [0 100])
set(AX(:), 'ytick', [])
set(AX(:), 'xtick', [])
set(H1,'color',colors(i,:));
set(H2,'color',colors(i,:));
i = i + 1;
end
set(AX(1),'ytick', [2:.2:3.3])
set(AX(2),'ytick', [0:20:100])
set(AX(:),'xtick', [0:.05:.5])
Thanks for the help!

Best Answer

1) During your loop, create an array of handles that you want.
h(i)=H1; % just add the handle for one of the three plots for each battery
mylabels{i}=['battery' num2str(i)];
2) After your loop, use the handles to make a legend.
legend(h,mylabels);