How do I make colorbars of subplots with different colormaps match for each subplot?

84 ビュー (過去 30 日間)
I'm making a figure with two subplots in Matlab 2017a. Each subplot has a different image with a different colormap. I want to have a colorbar for each subplot that matches the colormap of that subplot.
The problem is the colorbar of my first subplot does not match its colormap. Instead the colorbar of the first subplot incorrectly matches the colormap of the second subplot.
I'm using freezeColors and cbfreeze for each subplot as described in other questions on this forum. I am correctly getting different colormaps for each subplot, and the colorbar for the second subplot is correct, but the colorbar for the first subplot is not correct. What am I doing wrong?
Here is code that demonstrates the problem:
load clown.mat
image(X)
load penny.mat
image(P)
figure(1)
hFig=gcf;
set(hFig, 'Position', [50 50 300 500]);
subplot(2,1,1)
image(X);
colormap('gray')
hcb1=colorbar;
freezeColors
cbfreeze(hcb1)
subplot(2,1,2)
image(P);
colormap('jet')
hcb2=colorbar;
freezeColors
cbfreeze(hcb2)
Here is what the resulting figure looks like with the incorrect colorbar for the first subplot:

採用された回答

Greg Pelletier
Greg Pelletier 2017 年 4 月 18 日
I found the answer. There is no need for freezeColors or cbfreeze in Matlab 2017a. The trick is to use gca as the target in colormap. Here is the code that works correctly:
load clown.mat
image(X)
load penny.mat
image(P)
figure(1)
hFig=gcf;
set(hFig, 'Position', [50 50 300 500]);
subplot(2,1,1)
image(X);
colormap(gca,'gray')
hcb1=colorbar;
subplot(2,1,2)
image(P);
colormap(gca,'jet')
hcb2=colorbar;
The resulting plot looks like this with correct colorbars matching the different colormaps of each subplot:
  3 件のコメント
Stuart-James Burney
Stuart-James Burney 2020 年 1 月 17 日
This is genius!!! Thank you

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeBlue についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by