How can I create a custom 3-color gradient scale using imagesc?

44 views (last 30 days)
Hello, I am very new to Matlab and would appreciate any insight, and detailed explanations if possible.
I am using imagesc to plot a heatmap of my data that ranges from 0 to 100, in increments of 5 (21 different possible values 0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100). I would like to create a 3-color gradient scale (such as is possible with conditional formatting in excel). I would like the gradients to go from blue (0to50), yellow(55to80), and red(85to100). Is this possible?
Thank you in advance.

Answers (1)

Image Analyst
Image Analyst on 3 Sep 2015
Try this:
% Initialize a color map array of 101 colors.
colorMap = zeros(101, 3);
% Make blue ramp
colorMap(1:51, 3) = linspace(0, 1, 51-1+1);
% Make yellow ramp
colorMap(52:86, 1) = linspace(0, 1, 86-52+1);
colorMap(52:86, 2) = linspace(0, 1, 86-52+1);
% Make red ramp
colorMap(87:101, 1) = linspace(0, 1, 101-87+1)
% Create a sample image of a ramp.
heatMap = repmat(0:100, [200, 1]);
% Display it.
imagesc(heatMap);
% Apply the colormap and show the colorbar
colormap(colorMap);
colorbar;
  3 Comments
Image Analyst
Image Analyst on 4 Sep 2015
I don't see how what I provided doesn't do that. Each array element (pixel) has a value, and the color it appears as is the color you made in colorMap. If you want something like that, try this:
% Create a sample image of a ramp.
heatMap = repmat(0:100, [200, 1]);
% Display it.
imagesc(heatMap);
% Initialize a color map array of 101 colors.
colorMap = jet(20);
% Apply the colormap and show the colorbar
colormap(colorMap);
colorbar;
axis image;
The convention in MATLAB is to have higher values at the top of the colorbar, not the bottom like you have it there in Excel, but maybe you can flip it. Just use flipud(colorMap) to flip the colormap, then write the tick marks manually.
lenny466
lenny466 on 4 Sep 2015
Hi Image Analyst, Thank you for responding; I really appreciate your help. I was able to figure out how to add the jet(20) color map before you responded, but I am facing two issues with that.
1) I would like to have the yellow center shifted to the "80" point (vs "65") and 2) How can I make the NaNs in my data show up as white/background color? I have searched all over for a good answer to this and have tried many different things, but I can't find a good solution. Currently, the NaNs are set as the lowest value blue color.
Any help would be appreciated, and again, I'm super thankful!

Sign in to comment.

Categories

Find more on Colormaps in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!