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);

ax(2) = subplot(2,1,2);
% Use the axis handle as first input argument
% to colormap
Multiple colormaps in one figure.

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 

% 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'),...
% Plot the stream network               
% Make axis invisible
% Create a colorbar
hc = colorbar(h_ax_stream,'Location','southoutside');
% ... and label it
hc.Label.String = 'ksn';
% Adjust color range
caxis(h_ax_stream,[0 200])
% Perfectly align both axes
set(h_ax_stream,'position', get(h_ax, 'position'),...
                'DataAspectRatio',[1 1 1]...
% Link both axes so that you can zoom in and out            

% Resizing the figure may screw it all. Using the figure
% property ResizeFcn makes sure both axes remain perfectly
% aligned
hFig.ResizeFcn = @(varargin) ...
    set(h_ax_stream,'Position',get(h_ax, 'position'));
Multiple colormaps in one axis.

The trick is to use additional axes. The difficulty lies in perfectly aligning them and to make alignment robust against resizing the figure.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.