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
multiplecmaps.png
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 
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';
% Adjust color range
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            
linkaxes([h_ax,h_ax_stream],'xy');

% 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'));
multipleaxes.png
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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.