File Exchange

image thumbnail

freezeColors / unfreezeColors

version 1.3 (146 KB) by

Use multiple colormaps per figure! Version 2, now works for many types of objects, not only images.

120 Ratings



View License

Editor's Note: This file was selected as MATLAB Central Pick of the Week

Update: 2017: As of Matlab 2014b, this may no longer be needed as MATLAB now allows multiple colormaps per figure--please see my comment. Thanks!
Version 2.3, 3/2007
          (*What's NEW: 9/2010, A colorbar solution)

Problem: There is only one colormap per figure, so all plots share the same colormap. Often one wants different colormaps.

Solution: This function pair provides an easy way to have plots using different colomaps in the same figure.

colormap hot
freezeColors %freeze this plot's colormap

colormap hsv % won't change any frozen plots!

**** COLORBAR WORKAROUND (NEW 9/2010) ****
** Note: in recent versions of MATLAB the colorbar is reinitialized
** whenever you call COLORMAP, which undoes the effects of freezeColors.
** Suggested solution: Use the function CBFREEZE, by
** Carlos Adrian Vargas Aguilera, located in the fileexchange

h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar)

%Colorbar workaround example

Since Carlos has made a nice solution, I have chosen not to duplicate his efforts. Please use his fine code.


freezeColors Freeze colors of plots, making them immune to later changes in the colormap. Converts colors of many graphics objects (images, surfaces, scattergroups, bar plots, patches, etc--anything using indexed CData) to [r g b] truecolor.

unfreezeColors Reverses the effects of freezeColors. Restores the original indexed color data, allowing the colormap and caxis to again affect the plots.

Demo & Documentation in freezeColors_pub.html, test in test/test_main.m.

Comments and Ratings (180)

Igor J.

Thank you so much!


For some reason freezeColors changes the colors (or mapping of colors?) displayed on the patch...!!

John Iversen

John Iversen (view profile)

*From the Author*

Dear All,

I'm glad this has been of use to so many of you for so many years. It has been a great pleasure to read your reports and hear how you are using it.

**As pointed out, Matlab at last supports unique colormaps per-axis!! Hurray! I believe this has been the case from 2014b onwards.**

From the COLORMAP help:
COLORMAP(AX,...) sets the colormap for the axes specified by AX.
    **Each axes within a figure can have a unique colormap.** After you set
    an axes colormap, changing the figure colormap does not affect the axes.

See this page for an example.

So, for those using recent matlab, there may no longer be a need for freezeColors, and thus I bid thee a fond farewell.

For those on earlier versions, I hope freezeColors continues to work for you. If not, there are some excellent fixes posted below in the comments. Or you can email me at and I'll try to help as I can. I always enjoy seeing how you use freezeColors, so feel free to drop me a line.

Happy Holidays.



M.M (view profile)

Great! Thank you so much!

Ran wu

Ran wu (view profile)

when i used freezecolor(R2015a),it didn't work. i can't freeze the first colorbar.why?


Stoat (view profile)

For some reason freezeColors stopped working for me (R2015a), and as other users I was getting "While setting the 'CData'...Value must be a scalar..."
I added the following around line 147:
realcolor = squeeze(realcolor)

And now it works again for me.

Han Han

Hello, I have the same problem as Fedor.
When I create bar plots, legend colors for different subplots doesn't follow the "frozen" colormap. And all legends are colored according to the last "frozen" colormap.
After downloading cbfreeze.m and cbhandle.m (by Carlos Adrian Vargas Aguilera), I still can't freeze my colorbar.
I use Matlab R2015a.
Thank a lot!

Han Han


roy (view profile)



Eric (view profile)

WONDERFUL submission. Works like a champ. Thank you sooooo much!!!


SidSux (view profile)

Distinct colormaps for separate axes are natively supported in the newer versions of Matlab:


Sina (view profile)

I have the same/a similar problem as Lillian.. Can anyone help? Thank you in advance! I am using R2015b.

Error using
While setting the 'CData' property of 'Scatter':
Value must be a scalar, vector or array of numeric type

Error in freezeColors (line 157)


Also, even when I separate my plots into two subplots, I get an error here. Note there is no CData for object, but "interesting children" found by getCDataHandles() are all scatter objects.

Error using
While setting the 'CData' property of Scatter:
Value must be a scalar, vector or array of numeric type

Error in freezeColors (line 159)

Can anyone help me understand this error and why it's not working for me? I'm using MATLAB 2014b.

Thanks for any help!


What if you have two colormaps in the same plot (not in subplots)? I would like to show colormaps on colorbars for multiple color gradients (one is grayscaled edges and other is red scaled background).

I am not able to use freezeColors for within the same plot.. am I using it incorrectly?

Edden Gerber

Sorry, in my previous comment, the original line of code is of course:
idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors);

Edden Gerber

I propose a bug fix:

In line 122:
idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors-1);

But - this convert the range [0 1] not to the range [1 nColors], but rather to [0 nColors] (since ceil(0)=0). So you discretize the scale to nColors+1 possible values, and then crop out the lowest one in line 132:
idx(idx<1) = 1;

My fix is changing line 122 to:
idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * (nColors-1))+1;

Thanks for the useful function,


Cim (view profile)

freezeColors doesn't appear to work with contourf. Am I missing something? I'm using 2015a.

The following code results in two different colormaps, as expected:
pcolor(peaks); shading flat
pcolor(peaks); shading flat
colormap jet

However, with this code (contourf instead of pcolor), both subplots end up with jet colormap:
colormap jet

Do others have this same problem? Are there any workarounds for getting two contourf with two different colormaps in the same figure?

Thanks for your help.


Myles (view profile)

Kinfoon Wong

Kinfoon Wong (view profile)


TAY (view profile)

the program crash when i try to use th cbfreeze(h,'off'), anyone encounter this problem? This function is very useful, thank you author!!


David (view profile)

Does not work for me when using scatter in 2014a; erases the points on the plot when I call it.

Simon Henin

Simon Henin (view profile)

Worked like a charm. Thanks!

laurent grare

It seems that when plotting a scatter plot, the function does not work if the input data are rows (size(x) = [1 m]).
A simple re-arrangement of the data into columns fixes this issue.

Tarun Narayan

Matlab makes this process so complicated, but these scripts simplify everything tremendously.

Joris Kampman

Joris Kampman (view profile)

Danny Allen

This is so useful - many thanks !


Dan (view profile)

Thanks for this excellent code. I've used it many times without problems, but just ran into a problem today. I have a colormap with five colors. When I use freezeColors, it does in fact freeze the colors, but it reduces the number of colors from five to four. Any suggestions on how to fix this?


Dan (view profile)


Freezecolor was just what I needed to plot contours over map data and I have used it for a while. However, in MatLab 2012a and later freezing contourm results no longer works without some modification. There is a listener associated with this plot that remaps all the color levels whenever the colormap is changed thereby undoing the freezecolor changes.I solved this problem by switching the parent of all the countour's children from its hggroup typed parent to that of the parent axis. This disassociates the contour from the hggroup listener. This works for my application so far.

Scatterm does not have this listener and freezcolor works great, however, I came across one small error for an unusual case. If there is only one point in the scatter plot (my plots depend on user clicks and sometime degenerate to this point) then the color is of the wrong dimensionallity. The listener in scatterm that is triggered when the color is frozen has code that checks if the first dimension of cdata is 1 then the second dimension must be 3 or it will be ignored - not colored. The structure freezecolor passes in is 1x1x3. I put a check in freezecolor for object types ~patch (scatterm plots are hggroup type) that if size(realcolor,1)==1 then realcolor=squeeze(realcolor)'.

Oscar Chen

 Hi John Iversen,

  My name is Felipe Orellana, a graduate student at UC Berkeley. I work in Geophysics, doing numerical simulations in plate tectonics.

  Man, thanks a lot for your code, it's very helpful.

grateful for your submission,


 Hi John Iversen,

  My name is Felipe Orellana, a graduate student at UC Berkeley. I work in Geophysics, doing numerical simulations in plate tectonics.

  Man, thanks a lot for your code, it's very helpful.

grateful for your submission,



I don't know how to use it for GUIs. I have already downloaded the file.
My code is:
switch str{val};
    case 'Sphere'
         colormap copper;
         daspect([20 20 20]);
    case 'Contour'
         colormap spring;

The error I get is:
Undefined function 'freezeColors' for input arguments of type 'double'


MJ (view profile)

Jorge Real

ZZL Zhang


Carola (view profile)

Thank you for this very useful function. I love to use it.

However I seem to have a little problem with it. I'm using it with contourf with user-defined contour lines, and somehow the coloring of the fields changes when applying freezeColors while the colors of the colorbar remain the same with cbfreeze. To me it seems it has to do with the contour interval being a decimal number instead of an integer, but maybe there is another cause?

Here is a simple example of when it happens:

Z = peaks;
dc = 14/8;
c = -4:dc:10;
caxis([min(c) max(c)])
title('freezed colors')
caxis([min(c) max(c)])
title('no freeze')

Edward Byers

Works well with subplots

Klaus Mayer

Hi, very nice contribution.
I had a problem using the code in a gui environment. The problem is, that the current axis is not always that axis which is used for plotting, if you define an axis property in the plot command. You may than use freezeColors(axis_handle). But the caxis command in the code does not use that axis_handle. Therefor I changed in line 86: cax=caxis to cax=caxis(h). Than everything works fine.

Hi everyone. I found out how to freeze the colorbar as well. Actually, I got my answer from the test_main.m file of this submission. You should download cbfreeze.m and cbhandle.m (by Carlos Adrian Vargas Aguilera) and freeze your colorbar with these functions. Just make sure to download cbhandle.m as well or MATLAB will give you some handle errors.

load clown

Hi. This is great.
I have the same problem as Fedor. The colorbars that I add to my plots all have the same colors of the last entry for colormap. So now, my jet colormap has a gray colorbar.


Fedor (view profile)

Hi. Very nice submission.
The only problem I have encountered is that when I create bar plots, legend colors for different subplots doesn't follow the "frozen" colormap. And all legends are colored according to the last "frozen" colormap.
I use Matlab R2010a. Has anyone else experienced the same problem?
Thank a lot!

Jim K

Jim K (view profile)

kaiba Wong

I have a problem with freeze color..can someone please help. When I use it, the color of the plot takes the color from the subsequent plot

caxis([-0.5 1]);
        caxis([-0.2 0])
        axis([-2500 1000 -0.4 0.4])
         caxis([-0.5 1])
    Can someone please point out why is it not working? Thank you so much

Chad Greene

Chad Greene (view profile)

Does exactly what I wanted it to do with one simple command. Brilliant.


Wonderful submission. I have been looking for something like this for months. I have a little problem though. Using freezecolors and cbfreeze combination in MATLAB (R2010b) works fine on my subplots but I get the same colorbars in the different subplots.
In fact I get this following warning message:
Warning: You seem to be attempting to freeze a colorbar. This no longerworks. Please read the help for
freezeColors for the solution.
I would be glad if a workaround could be suggested


Jan (view profile)

Often wondered how to do that. Very cool


Jan (view profile)

Chris McGraw

Great code! One issue I noticed though is that representations of logical/binary data (at least using imagesc function) cannot be frozen using 'freezeColor' -- you must convert them to non-binary for it to have its effect, e.g. double(myBinaryData). No error is thrown or generated if binary data is used, it simply fails to freeze (took me 20 minutes to determine what was going wrong). This is not the first code I've noticed that behaves oddly (unexpected results, no errors generated) around logicals, so it might be more of a Matlab issue than the code itself.

Chris McGraw

Gaurav Rayal

This is so useful.

Martina Callaghan

Thanks! Super useful.

Great file. Makes my contourplots much nicer than what would have been otherwise possible. But it doesn't seem to work with matlab2tikz.

Liaofan Lin

Liaofan Lin


Adam (view profile)


Suti (view profile)

Richard Sims

Great piece of code! if anyone knows how to preserve the alpha command so i can keep the adjusted transparencies i would be extremely grateful!


Espa (view profile)

Thanks a lot for this very useful piece of code!

Jakob Sievers

Jakob Sievers (view profile)

Incredibly useful!


Manuel (view profile)

I was recommended to use this file in order to save all the intensity values of an image.
Reading the documentation I can see that it saves all the pixel info because the program is able to freeze and unfreeze the image and to restore it.

My questions are: Does the program save the info of each pixel (Index or Intensity Value, and position) when is asked to freeze it? Does the program save this info in any variable?

Thank you in advance and congratulations for your program.



Rems (view profile)

I have three binary masks that I want to display in one figure with three different color maps. However I always get the same color for the three masks, the function freezeColors is apparently not working for binary logical maps even after applying the change proposed by Mircea Ionescu (17 Oct 2011). Can somebody help?

Here is my code


Drew Compston

Drew Compston (view profile)

This function worked well for me using R2012a and imagesc and surf. Haven't tried for other types of plots like scatter (in one of the comments).

John Iversen

John Iversen (view profile)

Hello from the author.

I'm sorry people are having trouble with newer versions of Matlab. They keep changing things under the hood, in the name of progress.

I'm willing to help try to fix things, but it'll only work if you the users send more _details_. For starters:
What exactly doesn't work?
What is the error (if there is one)?
What do you expect vs. what do you see?
Important: Please send me simple demo code that demonstrates your problem. Simplify your code to the minimum that still shows the problem. This is invaluable.

It seems like a number of problems are focussed around the mapping toolbox. Please verify if you see the same problems if you instead use the standard graphics functions? That is, replace contourm and scatterm with contour and scatter, for example.

I would like to keep freezeColors working for everyone, but can only do so with your help.

You can send me these things off list at iversen AT


John Iversen

John Iversen (view profile)

Hello from the author.

I'm sorry people are having trouble with newer versions of Matlab. They keep changing things under the hood, in the name of progress.

I'm willing to help try to fix things, but it'll only work if you the users send more _details_. For starters:
What exactly doesn't work?
What is the error (if there is one)?
What do you expect vs. what do you see?
Important: Please send me simple demo code that demonstrates your problem. Simplify your code to the minimum that still shows the problem. This is invaluable.

It seems like a number of problems are focussed around the mapping toolbox. Please verify if you see the same problems if you instead use the standard graphics functions? That is, replace contourm and scatterm with contour and scatter, for example.

I would like to keep freezeColors working for everyone, but can only do so with your help.

You can send me these things off list at iversen AT


Emil Lundberg

Eran Mukamel

This doesn't work in R2012a - any updates/fixes? It would be much appreciated!

Thanks a lot mate! This is something I have tried for months but couldn't achieve. Your solution is awesome

Thanks a lot mate! This is something I have tried for months but couldn't achieve. Your solution is awesome

Thanks a lot mate! This is something I have tried for months but couldn't achieve. Your solution is awesome

Thanks a lot mate! This is something I have tried for months but couldn't achieve. Your solution is awesome


Miche (view profile)

Great stuff! Thanks

I found the trick. Actually I was plotting 3 subplots: 1 surfc + 2 contourf, and it doesn't work but when I changed the order as following:
2 contourf + 1 surfc (i.e. surfc at the end)
It works... very mysterious


Brad (view profile)

Problems with this function in r2012a -

I am still having problems getting this to work in release 2012a. I have tried Lucio's solution, but it didn't work. I have a subroutine that plots a contourm map, and passes out the handles of the axes, the contours and the figure. I then call freezeColor in the main routine, and I have tried addressing this to all three of those handles - different results, but none are desired (and none are right as they were in release 2009b)!

addressing the axes handle - I get two color bars with the desired color maps, but the contours which are plotted first all change to black.

Addressing the contour handle - generates an error "Error using get - Invalid Handle"

Addressing the Figure handle - I get the same color bar for the contourm plot and the scatterm plot, but the contours all turn black (they are over the maximum of the second colormap).

Any solutions? Any new functions out there? This was fantastic before the GD version change - but I notice John has posted anything in a while...


Phillip (view profile)

Fantastic! They should add something like this to the official Matlab release.


Lucio (view profile)

Ok, I solved it.

I had to use

sc_h = scatter(...)

instead of


although I confirm that the second way was alright also with previous Matlab versions (but not anymore).

Sorry for the double comment.


Lucio (view profile)

I'm having the same issue as Brad.

FreezeColors used to work with Matlab2009b and Matlab2011a, but now it works no more on the same code with Matlab2012a.

The line that makes my scatter plot disappear is



Georg (view profile)

Love this script and rely on it heavily. However I stumbled upon an issue, when using two axis in a figure, the caxis scaling would use the wrong axis and thus produce an erronenous scaling of the color.

A simple cax = caxis(h); in line 86 solved that for me


Brad (view profile)

I am having an issue with release 2012a. My code was written and employed FreezeColors as well as cbfreeze in release 2009a. FreezeColors no longer works - all of my contourm lines go black when I use scatterm to plot points on top. Is anyone experiencing similar issues? I haven't changed the code, but it doesn't work anymore.

Giovanni Ughi

Great tool! Thx for sharing!
One issue:
working with a GUI, calling
generates an error.

Need to call:
to solve the issue.
Any idea about this? Possible to fix?

Giovanni Ughi

Great tool! Thx for sharing!
One issue:
working with a GUI, calling
generates an error.

Need to call:
to solve the issue.
Any idea about this? Possible to fix?

Giovanni Ughi

Great tool! Thx for sharing!
One issue:
working with a GUI, calling
generates an error.

Need to call:
to solve the issue.
Any idea about this? Possible to fix?


Zhou (view profile)

Thank you very much!!!!!!

John Iversen

John Iversen (view profile)

== from the Author ==

Hi everyone. Happy New Year!

I wanted to belatedly comment on the problem people are having with eps/pdf exports ending up with pixellated text and lines. It's a bummer. Unfortunately, I believe this is an underlying feature of Matlab. Matlab has three methods for rendering plots, and this has an effect on printing to files, too. See "Impact of Rendering Method on the Output" at

In short, even if you print to a vector format like 'eps' or 'pdf' matlab will save _bitmaps_! The only exception is when using render mode 'painters'. If you open these resulting eps/pdf in a vector program like Illustrator you'll see the file is in fact a bunch of bitmap 'strips'. It would be so much better if Matlab saved the image parts of your figure as bitmaps but kept the lines and text as crisp vectors. Please contact Mathworks to complain/suggest this.


First, try

>> set(gcf,'renderer','painters')

on your plots and see if you like the result. If so, you're golden: With the 'painters' renderer will you get what you want--a vector format output with text (and presumably lines--I haven't verified this) as vector objects. However, you will lose many effects like transparency, lighting, etc, and some more advanced plots you will see an error as they cannot be rendered in this mode.

Otherwise, the workaround is to specify a _resolution_ when you print to eps or pdf:

>> print(gcf,'-depsc','-r600','file.eps')

It'll still just output a bitmap, but at least the text and contours will be rendered smoothly (at 600 ppi in this case. Use a higher number for even smoother results). The default is in fact '-r72' which is why you have been getting pixellated text and lines.

In this case, there's really no point in printing to eps or pdf, so you might as well use 'tiff' or another true bitmap format:

>> print(gcf,'-dtiff','-r600','file.tiff')

I tested this out on Koos Spee's nice example, and using R2010a. Hopefully this generalizes and helps people out. Let me know if so/not. Thanks, John

PS. Thank you for bug fixes (Mircea & Subhaneil). I'll upload a new version eventually...

Nice script, but the fact that you cannot export eps files is a big downside. I found a workaround to this with the info posted here:

Specifically, I wanted to plot a contour in the same axis as a gray scale image. This is an example of how to do this:

%Define the colormap

data = 255.*rand(100);
data2 = peaks(100);

h(1) = imagesc(data);
hold on
[C,h(2)] = contour(data2);
hold off

m = 64; % 64-elements is each colormap

cmin = min(data(:));
cmax = max(data(:));
C1 = min(m,round((m-1)*(data-cmin)/(cmax-cmin))+1);

cmin = min(data2(:));
cmax = max(data2(:));
C2 = min(m,round((m-1)*(data2-cmin)/(cmax-cmin))+1);
C2 = m+C2;

caxis([min(C1(:)) max(C2(:))])

%Fix the color bar so that it only dispalys the colors of the contour
colorbar('YLim',[65,128],'YTickLabel',[10 20 30 40 50 60])



Great tool.
One issue: this function does not work with logical data.
Modifying line 196 from:
if ~isempty(g.CData) && (isnumeric(g.CData)|| islogical(g.CData)) && size(g.CData,3)==1,
to :
if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1,

solves the issue.


Andrew (view profile)


Carl (view profile)


Maria (view profile)

Hello! Thank you John, this is a fantastic function. However I'm experiencing the same issues that Yongmin Jiang (May 2007) and Koos Spee (Mar 2010). Did anybody find a solution for this? I normally print my contour plots in epsc or pdf and they look very sharp and smooth and when I use freezeColors the contours and axis labels become very smudged and pixellated. This is very frustrating as creating subplots works so much better for me than individual figures. Did anybody find a solution to this? I played around with resolutions and different file formats to no avail.

Thank you!



Eva (view profile)

Brilliant function- thanks John.

However, I'm having an interesting problem with it when using contourf. If I run the following code line-by-line (ie: cutting and pasting each line into the command window one at a time), I get the correct image. If I copy and paste all lines of the code together into the command window, I get a completely different image. Note that this is NOT the case with imagesc, surf, etc.


colormap hot

colormap hsv

Why is this? Any ideas for how to fix it so that I don't have to run my code line-by-line?

Thanks much!

Hassan Naseri




I have a question, I would highly appreciate anyone's help as this thing is getting on my nerve!!!

I am using freezecolors, I find it very helpful however there is something about it :
I want to see the "index" of each pixel of my image when I use the "Data Cursor" bottom.

However after I apply freezecolors to my image I only see the "x" , "y" , and "RGB" values of each pixel but not the "index" value!

I was wondering if there is a way that I can see the "index" value as well?

Thanks so much,


Sieun (view profile)


olim (view profile)

Great package John! Thank you very much...
In my case its extremely useful overlaying severla meshs in one figure, with different colorbars.
However, it just turned out there might be some issues with the print command.
I always used saveas so far to save my figures to eps format. Now, as I just found out, for printing vector graphics from commands like pcolor or mesh you do better using the print command with the -painters option,e.g.

print(gcf,'-depsc', '-painters', '-r72', 'test1.eps');

If I use this on a mesh plot with several mesh layers, constructed with the freezeColors command before, the print function will only print out a figure with the last mesh plotted mesh layer. Is this a known issue or is there a simple fix for it.



Fran (view profile)

John Iversen

John Iversen (view profile)

Thank you for the answer, Irene. Did it work?

Eef, this is not something I can reproduce. freezeColors doesn't touch the labels, so it is a side effect of some sort. It could be a matlab bug due to change in the figure's renderer--I see similar problems when converting (set(gcf,'renender',...) between rendering modes. If you can narrow it down to the specific line in freezeColors that causes the change, it could give you a clue on what to ask mathworks about.

Matthias: The example you give works fine here. What is the error you're seeing? If you're having a problem with cbfreeze, you'll have to ask its author for help.


It save the colors if the current plot, but the colorbar is wrong. Using cbfreeze only gives error of invlaid handle for colorbar handle, so this does not work

hcb1 = colorbar('location','EastOutside');

This way it is not usable to me, any fix would be highly appreciated

Irene Laiz

To the author: great job!! Thanks so much for this wonderful routine!!

To Sophie's post (15 Nov 2010): There's a simple way to work around your problem by simply eliminating the handles after "colormap". I've modified your code below:

load clown;
figure('position',[100 100 500 500]),

h1 = axes('position',[0.1 0.1 0.4 0.4]);
imagesc(X); %Without handles
freezeColors; %Without handles

h2 = axes('position',[0.6 0.1 0.4 0.4]);
imshow(mat2gray(X)); %Without handles
freezeColors; %Without handles

Hope this helps!!


Sophie (view profile)

It's a really useful work! But I have a question. This script will work only with subplots?

Because I tried with handles and I do not obtain what I wish:

load clown;
figure('position',[100 100 500 500]),

h1 = axes('position',[0.1 0.1 0.4 0.4]);
h1 = imagesc(X);

h2 = axes('position',[0.6 0.1 0.4 0.4]);
h2 = imshow(mat2gray(X));

The two images that I obtain are both gray:-(

Eef Joosten

Great function!

But is there a solution for the upwards shifting of the first letter of the Ylabel while using freezeColors?
Simple example:
imagesc(linspace(0,10)); xlabel('Time (ms)'); ylabel('Frequency (Hz)'); freezeColors

I experience this in windows and unix. Also, it doesn't matter if I use ylabel or any vertical text string. It does not happen with xlabel and horizontal text strings. Any help would be greatly appreciated.


Li (view profile)

This is an extremely useful function.

Unfortunately, it froze my Matlab program every time I run it. I had to force quit Matlab to run another code.


Great function. I needed to make one small change to get it to work properly, Line 86:
cax = caxis;
cax = caxis(h);

This made sure it got caxis from the correct axis.

John Iversen

John Iversen (view profile)

Hello, I have uploaded a new version of freezeColors.

Changes: The main change is in documentation, finalizing the suggestion to use cbfreeze to freeze colorbars. There is also a fix to a problem in which caxis was changed in contourf plots.

I would enjoy hear about the kind of work users of this function are doing, and see examples of its use. (my email address is contained in the functions).

Thank you, John Iversen

Excellent utility. With experimentation, I found freezeColors can be called once for multiple axes with the same colormap and scale. I'm making a movie with a lot of graphics elements, so speed is an important consideration. Any additional insights on how to speed up the process welcome (

where do i need to put unzipped folder in order to use this function?


Adam (view profile)

Great function! Is there any way to preserve alphamap data on images? Once I call freezeColors, the alphamap data is still present but not displayed.


A note on my submission above - I realized setting CLimMode back to auto only worked because I had already frozen the colorbar using cbfreeze . If it is not already frozen, when CLimMod is reset to auto the colorbar loses its limits (undoing the whole purpose of line 159)


This function was just what I needed for a contouring GUI I have where the user can contour selectable datasets on a map. However, I found that the contour levels got stuck to that of the first contour even though it had been deleted.

 I found that at line 159 where the CLim data for the parent is restored this set the CLimMode to manual vs. auto. The CLim data held the data limits for the contour. Successive contours used these limits even though the data was not in this range.

Adding a line to reset the CLimMode back to auto solves this.

feili li

this is so amazing! i have been looking for a way to solve colormap problem for a while. thank you John!


Nora (view profile)

Just what I need. Thank you!

Weixin LI

Great file!

John Iversen

John Iversen (view profile)

====From the Author====

Hello everyone. I'm glad this function has been useful.

One noted problem is that freezeColors no longer works for colorbars. I am writing to say I have decided not to fix this because there is another function that solves the problem...

The problem:
In newer versions, Matlab reinitializes colorbars behind the scenes every time CAXIS or COLORMAP is called. This deletes the frozen colorbar, undoing the work of freezeColors. They're trying to be helpful...

A solution:
As noted above by David, there's an option that has worked for people, the function CBFREEZE by Carlos Adrian Vargas Aguilera. It is available at:

I don't think there's any point in reduplicating his good work, so I will update the description to recommend the following usage:

colormap hot
freezeColors %freezes plot's colors, as usual
cbfreeze %freezes colors of any colorbars

colormap jet

Please let me know if this works/doesn't work for you. I'll update the description and sample code at some point.

Koos Spee

Got the same problem as Yongmin Jiang (May 2007). Made a quick example (as no solution has yet been posted).


clear all
close all hidden





set(gcf, 'Position', [400 400 FigureWidth FigureHeight], 'PaperUnits', 'Points',...,
    'PaperSize', [FigureWidth FigureHeight])

subplot('position', [0.1 0.2 0.40 0.70])
title('Not so nice', 'FontName', 'Arial', 'FontSize', 8');

subplot('position', [0.55 0.2 0.40 0.70])
title('Not so nice I', 'FontName', 'Verdana', 'FontSize', 6');
xlabel('XLabel Test','FontSize', 6');



    fillPage(gcf, 'margins', [0 0 0 0], 'papersize', [FigureWidth FigureHeight]);
% ttp://

    dos(['epstopdf ', fi]);
    fprintf('done!\n Figure saved\n')


Any idea to prevent the 'bitmapping' of labels/ticks?

Is it possible that I specify colors for ranges and always use those colors e.g. 0.2 -0.4 should always be represented by red color?


Reyna (view profile)




David (view profile)

Hi everybody!

For people having problem with the fixing of the colorbar (not only the colormap) I suggest you the combination with cbfreeze:


which worked fine for me!


John Iversen

John Iversen (view profile)

Fix for error pointed out by Daniel Armyr (11Aug): "image; freezeColors"

after the line: idx = cdata;
>insert the line: idx = floor(idx);

This will take care of the problem. Thanks for pointing it out.

Ian Howat

Ian Howat (view profile)

Great work!


David (view profile)


I using the freezing colorbars with 'v6' as you said. But this way I cannot define the location of the colorbar. Is there any simple solution for it. If I use

hc = colorbar('location',...)

it doesn't work anymore as 'v6' is missing...

Any ideas?

Thanks a lot,



Pearl (view profile)

Daniel Armyr

Daniel Armyr (view profile)

Neat program, but I found a bug:
Running the following line:
>>image; freezeColors

gives the following error message:
??? Subscript indices must either be real positive integers or logicals.

Error in ==> freezeColors at 136
        c = cmap(idx,i);

Placing a breakpoint and looking at idx on the line in question reveals that idx consists of floating point numbers and not integers at that point.

Unfortunately, I do not have enough of an understanding of the program to present a fix.

cool! helps to solve my problem! :D

John Iversen

John Iversen (view profile)



I'm really sorry not to respond earlier--I had no idea about the recent posts!

There is a workaround for the problem with freezing colorbars:


It works for me as of 2009a, so I expect it will work for other earlier versions.

To silence the warning messages,

should be run (once per session--put it in 'startup.m')

I hope this helps. Please let me know if not.

Best regards,


Great little tool, that doesn't work on colorbars in the latest version of Matlab.

Liam, it would be great if you could post your quick fix!

Jochen Rau

Had some problems with two axes, one image in each with a colormap with 255 entries. Using freezeColors a wrong color number is detected which results in distorted images.

adding a (h) behind colormap in line 81 and caxis in line 83 solves this, so that the lines look like:
81: cmap = colormap(h);
83: cax = caxis(h);

Nevertheless: Excellent work!
This fixes a Matlab flaw (colormap should be an image or axes property).

Alessio Rucci

Hi, I'm trying to plot in the same figure (not in different subplot of thesame image) two different data with different colorbar, but if I use freezeColor it doesen't work....


figure,contour3(X,Y,Z1); axis xy; colormap hsv;
freezeColors; freezeColors(colorbar);
hold on;contour3(X,Y,Z2); axis xy; colormap jet;
freezeColors; freezeColors(colorbar);

is it possible to have both the colorbars, one for each data?


Arnaud Laurent

Arnaud Laurent (view profile)

Thanks, you solved my problem! Nice work.

Excellent Work!

Anthony Lamb

Very good tool John. Unfortunately when used to have two color maps and colorbars on the same plot is seems to change my surface plot colors to those that match the OpenGL renderer.. The colorbars are ok it's just that little hick up... Any suggestions on a fix????
Oh.. Liam I'd like to get my hands on your quick fix as well..

To follow up: The problem is when you change the colormap and not easily solved in the freezeColors / unfreezeColors. I have created a simple fixme to get round it which I can provide if anyone needs it.

Like Jody I have been having issues with the colorbar. I can't seem to get them to stick to selected colormaps, I'm using R2007b

Jody Klymak

Jody Klymak (view profile)

To follow up: colorbar.m appears to redraw the image when the colormap is updated. There is a callback to "FigureChangedColor" that erases the old image and makes a new one. So the cdata that was set in the old colorbar is erased and replaced when colormap is called. Not sure how to get around it.

Jody Klymak

Jody Klymak (view profile)

Yes I can't figure out how to make 2008a/b colorbars freeze either.


We had to drape P wave velocities values over seismic amplitudes, therefore we needed two different colormaps.
Playing arount with freezeColors and Transparency did the trick !
Many thatks

David Lei

unfortunatly I got an errormessage after executing the demoprogram. I have got Matlab 6.5. Is this the problem?

subplot(2,1,1); imagesc(peaks); colormap hot; freezeColors

subplot(2,1,2); imagesc(peaks); colormap jet; freezeColors

??? Error using ==> nargchk
Too many input arguments.

Error in ==> D:\MATLAB6p5\work\freezeColors.m (checkArgs)
On line 206 ==> error(nargchk(0,3,nargs,'struct'))

Error in ==> D:\MATLAB6p5\work\freezeColors.m
On line 75 ==> [h, nancolor] = checkArgs(varargin);

Frank Leone

Thanks a lot, does exactly what I wanted. An additional feature, obvious but not mentioned, that it is also usable to use multiple colormaps within one set of axes using. For example:

plot (...)
colormap (...)
hold on;
plot (...)
colormap (...)

It is rather slow though for big plots, but that isn't a real problem.

Ting-Chieh Lin

This code is very useful. However, it seems works only for the colormap. The colorbar cannot work in Matlab 2008a.

Carlos Adrian Vargas Aguilera

Excellent function John. I just submited a function that frozen the colorbar map too for MATLAB 2007B, you should check it out: IMAGESCNAN


Irian O

Excellent work!

Eduardo Gonzalez

Excellent, but it did not work on colorbars in Matlab R2007b

Leo B

Great job!
Works great for plotting different plots and colormaps with hold on in the same figure and axes.

Bram van Hoof

Seems like an excellent way to solve this exact same problem that i have had!

Jiank L

thanks, great. but it seems that it can not work with `set' command, only work with 'imagesc', etc. so when plotting pic. in a for loop, we have to use multiple 'plot', but not 'set'. Maybe one can add a handle in freezeColors? :


Ryan Van Fleet

The perfect fix to my problem my multi-color-mapping problem. Very Handy. I had to comment two lines out of the freeze file that produced errors. After that worked great.

Damien G

I can now superimpose a color pseudocolor plot on another one containing a gray-scale colormap. It works, it's great. Many thanks.

Frank Bahr

This is exactly what I was looking for. Thank you, guys!

John Iversen

Yongmin, Unfortunately, those issues sound like general issues with Matlab graphics, not freezeColors. I have not encountered such problems, but if you have an example, I can look at it to see if there is a workaround. However, you may have better luck contacting Mathworks support directly.

Yongmin Jiang

Another side effect is the text of the figure is going to bitmap as well(does't look good), and when you save the figure in .eps, .jpg or other format, the picture quality is not as good, and the size of the figure is big.

Chris K

Oops, apologies! I just noticed the freezeColors(colorbar) option. Now I'm satisfied!

Chris K

A really great tool, but I am having a problem where the colormap of the colorbar of the first subplot is reset to the colormap of the second subplot. Any suggestions?

John Iversen


Thanks for the comment. My apologies. I noticed this problem as well, and it has been fixed. However, the newest version is not up yet. Please check back in a few days. In the meantime, I'm happy to email the newer version to you.

John Iversen

Andrew Stevens

It is a good attempt at patching a fundamental problem in ML.

However, when I try to use it with a colorbar, the function resets the scale of the colorbar to go between 0 and 1. The same thing appears to happen in the author's demo.

Does anyone know how to get around this problem? I tried first freezing the colorbar and then the axis and vice-versa (without luck).

Gleb Tcheslavski

very handi! Thank's!

Anne Marie treguier


Very good, useful function. Thanks.

Samuel Tucker

very sweet... also appears to work for R13.

p p

Is there a version for matlab R13 ?

J Roering

simple, easy, works perfectly, THANKS for saving from the "CLim" script offered with the matlab help section.

John Iversen

Note from author:
A second, updated version (2.1) uploaded 9/5/06. I realized v2 didn't freeze colors of bar plots, so that was added. Comments welcome.

Darren M

Was bashing my head off the wall trying to get a grayscale image to be beside a hot and 2 personalized colormaps for a publication. Thanks much!

Mike L

It's just what I need and does the job very nicely. Excellent script.

John Iversen

From the author:
A change was made to allow freezeColors to work with scaled, integer images.

Thanks to O. Yamashita for suggesting this.

The new version will appear in a few days (once reviewed by the Mathworks). In the meantime, the corrected line reads:
 idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors);

Thank you for the interest.

O Yamashita

This is a very nice tool!!
BTW, there may be a bug on line59,
  idx = ceil( (cdata - cax(1)) / (cax(2)-cax(1)) * nColors);

when 'cdata' is of type "uint", many entries of (cdata - cax(1)) / (cax(2)-cax(1)) could be zeros. This can be avoid by changing to

idx = ceil( (cdata - cax(1))*nColors / (cax(2)-cax(1)));

Hope this helps.

A. Brunner

What a nice tool. I was about to start writing my own little program, but why re-inventing the wheel?

Thank you for saving me time and nerves!

Anita D

ahh, it freezes the colorbars too! took me forever to figure out, but is awesome!

Anita D

really great, thank you so much, you saved my gui! now if i could only freeze the colorbars...

Anil Seth

What a fine file this is.

PB '

Well done! This is absolutely one of my all time favourites in the file exchange. /PB



Updating to reflect the possible obsolescense.


Change documentation to suggest using cbfreeze to freeze colorbars
Fix to preserve caxis for objects within hggroups (e.g. contourf)


Added workaround for problem freezing colorbars

Bug fix.

Add handling of some standard hggroup-based plot types: bar (bargroups), scatter (scattergroups).

New version, now works on all graphics objects, whereas before it worked only on images.

Allow freezeColors to correctly handle scaled integer cdata. Thanks to O. Yamashita for pointing this need out.

Additional usage info was requested for freezing a colorbar

MATLAB Release
MATLAB 7.10 (R2010a)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video