Modify colorbar ticks and color range

2019-07-25 08:57发布

问题:

This question is following on from a previous question about HSV color space.

Let's say I have two arrays A and B, where A are my data points (2D) of interest to be shown in the colorbar and B is an RGB image transformed from the HSV color space where: Hue is in the interval [0.25-1] (corresponding to normalized A values 0.25-1), Saturation = 1, Value in interval [0-1] (corresponding to some other values).

When displaying B with imshow, I want to create a matching colorbar with ticks that correspond to the value range from A.

First difficulty that I'm facing is that I want my Hue to be in the interval [0.25-1] and hence I only need a certain part of the hsv colorbar to be displayed.

Second difficulty is that I need to match the value range from A to the colorbar.


Example code:

A = rand(30,30)*0.4;        % Values range from 0 - 0.4
X = rand(30,30)*100+100;    % Values range from 100 - 200

A_n = A / (max(A(:))/0.75) + 0.25; % "Normalize", with range 0.25 - 1

X_n = X / max(X(:));               % Normalize, range 0 - 1

colorRGB = NaN([size(A),3]);       % preallocate

for ii = 1:size(A,1)     
  for jj = 1:size(A,2)
    colorRGB(ii,jj,:) = hsv2rgb([A_n(ii,jj),1,X_n(ii,jj)]); % turn into RGB
  end 
end

imshow(colorRGB),            % display image
colormap hsv; cb = colorbar(); 

In the example you can see that the colourbar covers the whole hsv range and has ticks from 0 - 1.

What I want it to be is showing only the upper 75% of the hsv range with ticks from 0 to max(A(:))

The correct colorbar assuming that max(A(:)) = 0.35 should look like this:

(you can see that I just cropped it, but that should not be necessary either)

回答1:

In order to do that you need 2 things. First crop the colorbar, bu setting its limits. Secondly, change the text in the labels of the colobar, but to make sure they are in the rigth places, you also need to set the positions of them manually. Hopefully the code makes sense:

cb = colorbar(); 
set(cb, 'ylim', [25 100])
set(cb, 'XTick', [25:15:100])    % modify values if you preffer
set(cb,'XTickLabel',strsplit(num2str([0.25:0.15:1])));