Multiple colormaps in one axis

Posted on Updated on

I recently mentioned that MATLAB now lets you easily use different colormaps in one figure. The trick is to provide the axis handle as first input argument to the colormap function call.

DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');
ax(1) = subplot(2,1,1);
imagesc(DEM);
colorbar;

ax(2) = subplot(2,1,2);
imagesc(DEM);
% Use the axis handle as first input argument
% to colormap
colormap(ax(2),landcolor);
colorbar

However, how do you use multiple colormaps in one axes? That’s a little more tricky. Below, you find commented code that shows how to plot a colored and hillshaded DEM together with a stream network colored with ksn-values.

% Some data (DEM and ksn of river network)
DEM = GRIDobj('srtm_bigtujunga30m_utm11.tif');
FD  = FLOWobj(DEM);
A   = flowacc(FD);
S   = STREAMobj(FD,'minarea',1000);
k   = smooth(S,ksn(S,DEM,A),'K',1000);

% Create a new figure
hFig = figure;
% Call imageschs which has some parameter/value pairs
% to control colormap and colorbar appearance
imageschs(DEM,[],'colormap','landcolor',...
'colorbar',true,...
'colorbarylabel','Elevation');

% Get the current axes
h_ax = gca;
% Create a new axes in the same position as the
% first one, overlaid on top.
h_ax_stream = axes('position', get(h_ax, 'position'),...
'Color','none');
% Plot the stream network
plotc(S,k,'LineWidth',2);
% Make axis invisible
set(h_ax_stream,'Color','none');
% Create a colorbar
hc = colorbar(h_ax_stream,'Location','southoutside');
% ... and label it
hc.Label.String = 'ksn';
caxis(h_ax_stream,[0 200])
% Perfectly align both axes
set(h_ax_stream,'position', get(h_ax, 'position'),...
'XLim',xlim(h_ax),...
'YLim',ylim(h_ax),...
'DataAspectRatio',[1 1 1]...
);
% Link both axes so that you can zoom in and out