MATLAB: Custom colormaps and color bars

colorbarcolormapcustom colormaplegend

Running MATLAB R2013a
I am using a custom colormap created with the colormap command on a plot. When I add a legend, the legend is in the correct color order. However, when I add a colorbar, it uses the 'jet' colormap. How do I get it to use my custom colormap? I included the relevant code below:
%setting the line color order where varycolor is from matlab central
numpowers = 50; %(usually ~20-100)
clrmap = colormap(varycolor(numpowers)); %sets line color order
figure('OuterPosition',[100 100 1000 640],'name',strcat('RLplot',devname),'numbertitle','off');
axes('FontSize',20,'FontName','Times New Roman','ColorOrder',clrmap);
grid on;
hold all;
box on;
for i = 1:length(structkey)
%each structure element in the structure contains a dataset
%a new color is assigned for each structure element
%each structure element corresponds to a number, say 1:1:50
eval(['RL = RLdata.' char(structkey(i)) ';']);
L=RL(:,1); %#ok<NODEF>
R=RL(:,2);
% Least squared linear fit to data
x=0:3:24;
fitcoeff = polyfit(L,R,1);
fiteqn = polyval(fitcoeff,x);
%Plot data
plot(L,R,'x',x,fiteqn,'-','Color',clrmap(i,:),'LineWidth',1.5);
%Write the string that will become the legend --> how I did the legend
% tmplgd = char(structkey(i));
% tmplgd = str2double(tmplgd(2:end-2))/1000;
% legendstr(2*i-1,1) = cellstr(sprintf('%0.3f %s', tmplgd, '\muW/\mum^3')); %#ok<AGROW>
% legendstr(2*i,1) = cellstr(sprintf('%s %0.1f %s %0.1f', 'y =', ...
% fitcoeff(1,1), 'x +', fitcoeff(1,2))); %#ok<AGROW>
end

Best Answer

When trying to match colors of lines for objects plotted one at a time in a loop, I usually find it easier to manually set line colors, rather than trying to rely on the color order of the axis. For the record, your example does this; even though you set a color order you never actually use it, since you override the defaults with your specific colors. Keep in mind that the colormap (of a figure) and color order (of an axis) are two different things, and need to be set separately.
cmap = jet(5);
figure;
hold on;
for ii = 1:5
y = rand(10,1);
h(ii,1) = plot(1:10, y, 'color', cmap(ii,:));
h(ii,2) = plot(1:10, y+0.1, 'color', cmap(ii,:), 'linestyle', '--');
end
legend(h(:,1), {'one', 'two', 'three','four','five'});
colormap(cmap);
colorbar;