Search code examples
matlabdata-visualizationmatlab-figurecolorbarcolormap

How to add a scaled color bar to line plots using a colormap in MATLAB?


The answer to Matlab colormap line plot explains how to use color maps with line plots, but how can a scaled color bar be added to the figure, like with a scatter plot?

xHorz = [0:0.001:2*pi];
nPts = numel(xHorz);
x = zeros(nPts,1);
x(:,1) = xHorz;
y = sin(x);

noiseMag = 1;
yNoise = y + noiseMag*randn(nPts,1);

winSizes = [100:100:2000];
nWins = numel(winSizes);

ySm = zeros(nPts,nWins);
for iWin = 1:nWins
    ySm(:,iWin) = smoothdata(yNoise,'loess',winSizes(iWin));
end

xScatter = repmat(x,1,nWins);
zScatter = repmat(winSizes,nPts,1);

f1 = figure;
scatter3(xScatter(:),zScatter(:),ySm(:),2,zScatter(:),'filled')
cbar = colorbar;
cbar.Label.String = 'Smoothing Window Size';

f2 = figure;
lineColors = parula(nWins);
for iWin = 1:nWins
    plot(x,ySm(:,iWin),'Color',lineColors(iWin,:),'LineWidth',2);
    hold on
end

2D line without colorbar:

3D scatter with colorbar:

I believe the smoothdata() function requires R2017a or later.


Solution

  • After plotting your lines just like you do now, you can add the color bar as follows:

    colormap(lineColors);
    cbar = colorbar;
    cbar.Label.String = 'Smoothing Window Size';
    N = 5;    % number of ticks
    cbar.Ticks = linspace(0,1,N);
    cbar.TickLabels = linspace(winSizes(1),winSizes(end),N);
    

    By default, the color bar goes from 0 to 1. I simply changed the labels associated to this interval. This produces:

    Note that I used lineColors as the color map for the figure. This is what determines the colors in the color bar. You can also do colormap parula to get a smoother color gradient.


    An alternative is to change the actual intervals. The plot's axes have a CLim property that directs this. You could thus simply do:

    colormap(lineColors);
    set(gca,'clim',winSizes([1,end]))
    cbar = colorbar;
    cbar.Label.String = 'Smoothing Window Size';