How to obtain a cutsomized colorbar at certain color value range?

3 views (last 30 days)
Hi,
I would like to obtain a customizd colorbar that has a range from 0-24.
I would like to paint black color for the points falling between 0-6 in colorscale,
paint red for the points falling between 6-18 in colorscale,
again paint black for the points falling between 18-24 in colorscale.
Any suggestions would be greatly appriciated.
scatter(X_axis_val,Y_axis_val,20,Z_axis_val)
MyColBar = [0 0 0; 1 0 0; 0 0 0];
colormap(MyColBar);
caxis([0 24]); colorbar;
The data is as attached below.
Thank you in advance.

Accepted Answer

DGM
DGM on 20 Feb 2023
Edited: DGM on 20 Feb 2023
You can have a nonuniform discrete colorbar, but it's a bit convoluted:
Drawing from the examples at that link:
% some fake data
x = linspace(0,24,50);
y = x;
z = x;
% intervals/categories in Z (or C)
% the span of this vector defines caxis/clim
zb = [0 6 10/sqrt(2) 18 24];
% interval/category colors
CT0 = lines(numel(zb)-1);
% generate expanded color table & info
nmax = 256; % maximum table length
[CT cidx] = intervalct(zb,CT0,nmax);
cidx1 = cidx(:,2); % trailing block indices
% color data as an RGB color table
% this can be generated however you see fit (imquantize(), etc)
% note my assumption of behavior on bin edges
C = ones(size(z));
nk = numel(zb)-1;
for ck = 1:nk
if ck == 1
C(z<zb(2)) = 1;
elseif ck == nk
C(z>=zb(nk)) = nk;
else
C(z>=zb(ck) & z<zb(ck+1)) = ck;
end
end
C = ind2rgb(C,CT0); % convert to RGB
C = reshape(C,[],3); % reshape into Mx3 color table for use with scatter()
% plot the scatter
hs = scatter(x,y,20,C,'filled');
colormap(CT) % use the expanded colortable
cb = colorbar;
cb.Ticks = zb;
caxis(imrange(zb));
grid on

More Answers (1)

Walter Roberson
Walter Roberson on 20 Feb 2023
MyColBar = [0 0 0; 1 0 0; 1 0 0; 0 0 0];
You cannot have color sections of different widths, but you can duplicate colors.
  1 Comment
MP
MP on 20 Feb 2023
Edited: MP on 20 Feb 2023
Ah! Thanks for the clarification! Could you please suggest how to know the default color section width on a colorbar? In my case I have 0-24 basically 24-sections. So May I assume that I will have to copy the color code 24-times?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!