How do I plot 2 images, each with a different colormap and CLim in a single subplot?

146 views (last 30 days)
Liron McLey
Liron McLey on 6 Jan 2021
Edited: Adam Danz on 8 Jan 2021
I have the 2018a version of matlab.
I want to plot a background image and an overlaid delta image that is partially transparent in the same subplot. The background needs to be grayscale and the delta image would be some other colorful colormap, the color limits of each image are also different.
Now, I know how to do this in a single figure - you just create 2 axes, one on top of the other, and then each axes is treated seperately. You can also physically see there are 2 axes in the Plot Tools window.
BUT, when I try to do the same thing in subplot, it doesn't create 2 seperate axes, but just comes back to the original axes ploted with the first subplot(...). In the Plot Tool window you can see there is just 1 axes.
The different colormaps and CLim are essential here, I can't just use transperancy alone.
I'd appreciate your help :)
Example - the following code works great [single figure]:
ax1 = axes;
hold on;
im1 = imagesc(image1,'Parent',ax1)
ax1.CLim = [0.4 1];
axis equal; axis tight;
ax1.Visible = 'off'
ax2 = axes;
im2 = imagesc(image2,'Parent',ax2,'AlphaData',0.4);
ax2.CLim = [-1 1]*1e3;
axis equal; axis tight;
ax2.Visible = 'off';
But, replace the ax1 and ax2 with these lines and it doesn't work anymore [a subplot inside a figure]:
ax1 = subplot(1,2,1);
ax2 = subplot(1,2,1);

Answers (1)

Adam Danz
Adam Danz on 6 Jan 2021
Edited: Adam Danz on 8 Jan 2021
Colormaps can only be set for a figure or for an axes and an axes can only have 1 colormap.
You'll need to create a second axes on top of the main axes to show both images with two different colormaps.
% Create main axis and then copy it.
fig = clf();
ax1 = axes(fig);
ax2 = copyobj(ax1,fig);
% Plot on both axes; specify axis handles!
C = peaks;
% Set colormaps
% Set all other properties of ax1 before moving on
% Finally, link the axis properties and turn off axis #2.
ax2.UserData = linkprop([ax1,ax2],...
{'Position','InnerPosition','DataAspectRatio','xtick','ytick', ...
'ydir','xdir','xlim','ylim'}); % add more props as needed
ax2.Visible = 'off';
Since the axis limits are linked, panning and zooming will affect both axes.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!