Code covered by the BSD License  

Highlights from
freezeColors / unfreezeColors

4.68627

4.7 | 109 ratings Rate this file 572 Downloads (last 30 days) File Size: 146 KB File ID: #7943
image thumbnail

freezeColors / unfreezeColors

by

 

28 Jun 2005 (Updated )

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

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information
Description

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.

Example:
subplot(2,1,1)
imagesc(peaks)
colormap hot
freezeColors %freeze this plot's colormap

subplot(2,1,2)
colormap hsv % won't change any frozen plots!
surf(peaks)
freezeColors
etc...

**** 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
** http://www.mathworks.com/matlabcentral/fileexchange/24371

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

%Colorbar workaround example
imagesc(peaks)
freezeColors
cbfreeze(colorbar)

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

FUNCTIONS

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.

Acknowledgements

This file inspired Improved Digital Image Correlation (Dic), Shaded Pseudo Color, Imagescnan.M V2.1 (Aug 2009), Multiple Colormaps, Statmask: Overlay Image With Coloured Statistical Mask, Neural Data Toolbox (Nd Tb), and Rgbmap Color Maps.

MATLAB release MATLAB 7.10 (R2010a)
Other requirements Tested under: 7.0.1, 7.3, 7.4, 2009a, 2010a Newer versions must use >> cbfreeze to properly freeze colorbars
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (156)
13 Oct 2014 Matt Eicholtz  
25 Sep 2014 David

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

17 Sep 2014 Simon Henin

Worked like a charm. Thanks!

29 Aug 2014 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.

14 Aug 2014 Tarun Narayan

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

20 Jul 2014 Joris Kampman  
10 Jul 2014 Danny Allen

This is so useful - many thanks !

19 May 2014 Dan

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?

19 May 2014 Dan  
13 May 2014 Catherine

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)'.

01 May 2014 Oscar Chen  
14 Mar 2014 Felipe Orellana

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,

Felipe

14 Mar 2014 Felipe Orellana

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,

Felipe

28 Feb 2014 Abdallah

I don't know how to use it for GUIs. I have already downloaded the file.
My code is:
switch str{val};
case 'Sphere'
[sx,sy,sz]=sphere(20);
ss=surf(handles.axes4,sx,sy,sz);
colormap copper;
daspect([20 20 20]);
freezeColors(ss);
case 'Contour'
cx=rand(7,7);
cy=rand(7,7).*sin(cx);
cz=rand(7,7).*cos(cy).^0.00005;
cc=contour3(handles.axes4,cx,cy,cz);
colormap spring;
freezeColors(cc);

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

19 Feb 2014 MJ  
18 Feb 2014 Jorge Real  
15 Jan 2014 ZZL Zhang  
07 Jan 2014 Carola

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;
figure
subplot(1,2,1)
contourf(Z,c)
caxis([min(c) max(c)])
colormap(jet(8))
h=colorbar;
freezeColors
cbfreeze(h)
title('freezed colors')
subplot(1,2,2)
contourf(Z,c)
caxis([min(c) max(c)])
colormap(jet(8))
h=colorbar;
title('no freeze')

05 Jan 2014 Edward Byers

Works well with subplots

19 Dec 2013 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.

04 Dec 2013 Pegah Hosseini

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.

example:
load clown
figure
subplot(1,2,1)
imagesc(X)
colormap(gray)
freezeColors
h=colorbar;
cbfreeze(h)
subplot(1,2,2)
imagesc(X)
colormap(jet)
freezeColors
h=colorbar;
cbfreeze(h)

04 Dec 2013 Pegah Hosseini

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.

01 Oct 2013 Fedor

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!

13 Sep 2013 Jim K  
07 Sep 2013 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

figure;subplot(3,1,1)
scatter(DiffPeP,DiffTWT_33_sh,40,DiffTWT_33_sh,'filled')
colorbar('peer',subplot(3,1,1));
set(gcf,'Colormap',mycmapTS)
caxis([-0.5 1]);
freezeColors(caxis)
cbfreeze;
cblabel('DiffTS','fontsize',10);

subplot(3,1,2)
scatter(DiffSo,DiffTWT_33_sh_F,40,DiffTWT_33_sh_F,'filled')
set(gcf,'Colormap',mycmap_s)
colorbar('peer',subplot(3,1,2));
caxis([-0.2 0])
freezeColors
cbfreeze;
cblabel('DiffTS','fontsize',10);

subplot(3,1,3)
scatter(DiffPeP,DiffSo,40,DiffTWT_33_sh_new,'filled')
axis([-2500 1000 -0.4 0.4])
colorbar('peer',subplot(3,1,3));
set(gcf,'Colormap',mycmapTS)
caxis([-0.5 1])
cblabel('DiffTS','fontsize',10);

Can someone please point out why is it not working? Thank you so much

03 Sep 2013 Danielle Ripsman  
14 Aug 2013 Chad Greene

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

12 Jul 2013 Onassis

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

02 Jul 2013 Jan

Often wondered how to do that. Very cool

02 Jul 2013 Jan  
28 Jun 2013 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.

28 Jun 2013 Chris McGraw  
03 Jun 2013 Arturo Moncada-Torres  
27 May 2013 Gaurav Rayal

This is so useful.

22 May 2013 Martina Callaghan

Thanks! Super useful.

05 May 2013 Edmund Brekke

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

01 May 2013 Liaofan Lin  
01 May 2013 Liaofan Lin  
26 Apr 2013 Adam  
24 Apr 2013 Suti  
24 Jan 2013 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!

24 Jan 2013 Espa

Thanks a lot for this very useful piece of code!

07 Jan 2013 Jakob Sievers

Incredibly useful!

10 Dec 2012 Manuel

Hi!
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.

23 Nov 2012 Muhammet  
18 Nov 2012 Rems

Hello,
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

subplot(1,3,1);imshow(Binary_Mask_1,map1)
freezeColors
subplot(1,3,2);imshow(Binary_Mask_2,map2)
freezeColors
subplot(1,3,3);imshow(Binary_Mask_3,map3)
freezeColors

17 Nov 2012 Drew Compston

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).

31 Oct 2012 John Iversen

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 nsi.edu.

Thanks,
John

31 Oct 2012 John Iversen

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 nsi.edu.

Thanks,
John

31 Oct 2012 Emil Lundberg  
15 Oct 2012 Eran Mukamel

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

05 Oct 2012 Damith Jinasena

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

05 Oct 2012 Damith Jinasena

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

05 Oct 2012 Damith Jinasena

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

05 Oct 2012 Damith Jinasena

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

07 Sep 2012 Miche

Great stuff! Thanks

16 Aug 2012 maryline bawedin

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

14 Aug 2012 Brad

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...

11 Jul 2012 Phillip

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

30 May 2012 Lucio

Ok, I solved it.

I had to use

sc_h = scatter(...)
freezeColors(sc_h)

instead of

freezeColors

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

Sorry for the double comment.

30 May 2012 Lucio

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

set(hh,'CData',realcolor);

29 May 2012 Georg

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

04 May 2012 Brad

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.

19 Apr 2012 Giovanni Ughi

Great tool! Thx for sharing!

One issue:
working with a GUI, calling
--freezeColors(h)
generates an error.

Need to call:
--axes(h)
--freezeColors
to solve the issue.
Any idea about this? Possible to fix?

19 Apr 2012 Giovanni Ughi

Great tool! Thx for sharing!

One issue:
working with a GUI, calling
--freezeColors(h)
generates an error.

Need to call:
--axes(h)
--freezeColors
to solve the issue.
Any idea about this? Possible to fix?

19 Apr 2012 Giovanni Ughi

Great tool! Thx for sharing!

One issue:
working with a GUI, calling
--freezeColors(h)
generates an error.

Need to call:
--axes(h)
--freezeColors
to solve the issue.
Any idea about this? Possible to fix?

22 Feb 2012 Martin Richard  
19 Jan 2012 Zhou

Thank you very much!!!!!!

05 Jan 2012 John Iversen

== 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 http://www.mathworks.com/help/techdoc/creating_plots/f3-103236.html#f3-103452

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.

=Workarounds=

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...

07 Dec 2011 Nicolas Weiss

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: http://www.mathworks.nl/support/tech-notes/1200/1215.html

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
colormap([gray(64);jet(64)])

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;

set(h(1),'CData',C1);
set(h(2),'ZData',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])

01 Dec 2011 Vincent

thanks!

17 Oct 2011 Mircea Ionescu

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.

05 Sep 2011 Andrew  
30 Aug 2011 Carl  
30 Jul 2011 Maria

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!

Maria

18 Jul 2011 Eva

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.

figure

subplot(2,1,1)
contourf(peaks)
colormap hot
freezeColors

subplot(2,1,2)
colormap hsv
contourf(peaks)
freezeColors

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!
-Eva

23 May 2011 Hassan Naseri

THANKS INDEEED

07 May 2011 Farzaneh

Hi,

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,
~F

26 Apr 2011 Sieun  
22 Apr 2011 olim

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.

Cheers
O

25 Feb 2011 Fran  
19 Nov 2010 John Iversen

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.

Thanks.

19 Nov 2010 Matthias Pospiech

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');
freezeColors;
cbfreeze(hcb1);

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

18 Nov 2010 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]);
set(h1,'visible','on');
colormap('jet');
imagesc(X); %Without handles
freezeColors; %Without handles

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

Hope this helps!!

15 Nov 2010 Sophie

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]);
set(h1,'visible','on');
colormap('jet');
h1 = imagesc(X);
ext_freezeColors(h1);

h2 = axes('position',[0.6 0.1 0.4 0.4]);
set(h2,'visible','on');
colormap('gray');
h2 = imshow(mat2gray(X));
ext_freezeColors(h2);

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

03 Nov 2010 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.

17 Sep 2010 Li

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.

15 Sep 2010 Subhaneil

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

This made sure it got caxis from the correct axis.

14 Sep 2010 John Iversen

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

10 Sep 2010 Howard Schoeberlein

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 (howard.schoeberlein@jhuapl.edu)

01 Aug 2010 Faisal Shahzad

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

23 Jun 2010 Adam

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.

10 Jun 2010 Catherine

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)

10 Jun 2010 Catherine

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.

02 Jun 2010 feili li

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

27 May 2010 Nora

Just what I need. Thank you!

20 Apr 2010 Weixin LI

Great file!

07 Apr 2010 John Iversen

====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:

http://www.mathworks.com/matlabcentral/fileexchange/24371-colormap-and-colorbar-utilities-sep-2009

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

%EXAMPLE
subplot(1,2,1)
colormap hot
imagesc(peaks)
freezeColors %freezes plot's colors, as usual
colorbar
cbfreeze %freezes colors of any colorbars

subplot(1,2,2)
colormap jet
imagesc(peaks)
freezeColors
colorbar
cbfreeze

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

22 Mar 2010 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
clc

%%

p=peaks(10);

%%

FigureWidth=400;
FigureHeight=200;

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

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

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

%%

Name='foo';

fillPage(gcf, 'margins', [0 0 0 0], 'papersize', [FigureWidth FigureHeight]);
% ttp://www.mathworks.com/matlabcentral/fileexchange/16566-fillpage

fi=strcat(Name,'.eps');
print(gcf,'-depsc',fi)


print(gcf,'-dpng','-r500','foo.png')

dos(['epstopdf ', fi]);

fprintf('done!\n Figure saved\n')

%%

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

22 Feb 2010 Samoline1 Linke

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?

02 Feb 2010 Reyna  
12 Jan 2010 Annette

Thanks!

09 Oct 2009 David

Hi everybody!

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

colorbar('location','SouthOutside');
freezeColors;
cbfreeze

which worked fine for me!

David.

08 Oct 2009 John Iversen

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.

25 Sep 2009 Ian Howat

Great work!

21 Aug 2009 David

Hello

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',...)
freezeColors(hc)

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

Any ideas?

Thanks a lot,

David

15 Aug 2009 Pearl  
11 Aug 2009 Daniel Armyr

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.

21 Jul 2009 Nazatul Naquiah Ahba

cool! helps to solve my problem! :D

16 Jul 2009 John Iversen

Hi,

** WORKAROUND FOR PROBLEMS WITH COLORBARS **

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:

freezeColors(colorbar('v6'))

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

To silence the warning messages,

warning('off','MATLAB:colorbar:DeprecatedV6Argument')

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

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

Best regards,

John

21 Jun 2009 Emanuele Ruffaldi  
04 Jun 2009 Daniel Golden

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!

05 May 2009 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).

21 Apr 2009 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....

[X,Y]=meshgrid(-10:10,-20:20);
Z1=sqrt((X/10).^2+(Y/10).^2)+2;
Z2=sqrt((X/10).^2+(Y/10).^2)-2;

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?

Thaks

21 Apr 2009 Arnaud Laurent

Thanks, you solved my problem! Nice work.

24 Mar 2009 Sebastian Thiele

Excellent Work!

08 Feb 2009 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..

22 Jan 2009 Liam Harrington-Missin

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.

21 Jan 2009 Liam Harrington-Missin

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

13 Dec 2008 Jody Klymak

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.

28 Nov 2008 Jody Klymak

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

15 Oct 2008 MARSSET Bruno

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
Bruno MARSSET

02 Sep 2008 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);

30 Jul 2008 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 (...)
freezeColors
hold on;
plot (...)
colormap (...)

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

18 Jul 2008 Ting-Chieh Lin

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

02 Jul 2008 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

Carlos

22 May 2008 Irian O

Excellent work!

25 Jan 2008 Eduardo Gonzalez

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

27 Sep 2007 Leo B

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

14 Sep 2007 Bram van Hoof

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

16 Aug 2007 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? :

%set(im3,'CData',cee1);
imagesc(cee1);
colormap(hot);
freezeColors;
freezeColors(colorbar);

28 Jun 2007 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.

26 Jun 2007 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.

06 Jun 2007 Frank Bahr

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

17 May 2007 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.

15 May 2007 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.

17 Apr 2007 Chris K

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

17 Apr 2007 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?

12 Apr 2007 John Iversen

Hi,

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

11 Apr 2007 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).

05 Apr 2007 Gleb Tcheslavski

very handi! Thank's!

20 Feb 2007 Anne Marie treguier  
17 Jan 2007 M C

Very good, useful function. Thanks.

04 Dec 2006 Samuel Tucker

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

26 Nov 2006 p p

Is there a version for matlab R13 ?

15 Oct 2006 J Roering

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

05 Sep 2006 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.

26 Jul 2006 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!

23 Jun 2006 Mike L

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

19 Apr 2006 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.

18 Apr 2006 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.

18 Apr 2006 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!

23 Nov 2005 Anita D

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

23 Nov 2005 Anita D

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

31 Aug 2005 Anil Seth

What a fine file this is.

06 Jul 2005 PB '

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

Updates
28 Nov 2005

Additional usage info was requested for freezing a colorbar

20 Apr 2006

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

05 Sep 2006

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

06 Sep 2006

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

06 Sep 2006

Bug fix.

16 Jul 2009

Added workaround for problem freezing colorbars

14 Sep 2010

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

Contact us