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.

4.50893
121 Ratings

155 Downloads

Updated

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.

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.

Comments and Ratings (181)

Zhang Qinghao

From 2014b versions,matlab can realize it without this function.
For example:
figure
ax1 = subplot(2,1,1);
surf(peaks)
colormap(ax1,spring)
colorbar
ax2 = subplot(2,1,2);
surf(peaks)
colormap(ax2,winter)
colorbar

Igor J.

Thank you so much!

Zhongwei Yang

zwyang@spaceweather.ac.cn

Tom BUGNON

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.
(http://ch.mathworks.com/matlabcentral/answers/194554-how-can-i-use-and-display-two-different-colormaps-on-the-same-figure#answer_172883)

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 jiversen@ucsd.edu 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.

John

M.M

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

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

roy (view profile)

thanks

Eric

Eric (view profile)

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

SidSux

SidSux (view profile)

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

http://ch.mathworks.com/matlabcentral/answers/194554-how-can-i-use-and-display-two-different-colormaps-on-the-same-figure#answer_172883

Sina

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 matlab.graphics.chart.primitive.Scatter/set
While setting the 'CData' property of 'Scatter':
Value must be a scalar, vector or array of numeric type

Error in freezeColors (line 157)
set(hh,'CData',realcolor);

Lillian

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 matlab.graphics.chart.primitive.Scatter/set
While setting the 'CData' property of Scatter:
Value must be a scalar, vector or array of numeric type

Error in freezeColors (line 159)
set(hh,'CData',realcolor);

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

Thanks for any help!

Lillian

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

Cim

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:
figure
subplot(121)
pcolor(peaks); shading flat
freezeColors
subplot(122)
pcolor(peaks); shading flat
colormap jet

However, with this code (contourf instead of pcolor), both subplots end up with jet colormap:
figure
subplot(121)
contourf(peaks)
freezeColors
subplot(122)
contourf(peaks)
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

Myles (view profile)

Kinfoon Wong

Kinfoon Wong (view profile)

TAY

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

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

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

Dan (view profile)

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

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,

Felipe

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

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'

MJ

MJ (view profile)

Jorge Real

ZZL Zhang

Carola

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

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.

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)

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

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

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

Chad Greene

Chad Greene (view profile)

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

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

Jan

Jan (view profile)

Often wondered how to do that. Very cool

Jan

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

Adam (view profile)

Suti

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

Espa (view profile)

Thanks a lot for this very useful piece of code!

Jakob Sievers

Jakob Sievers (view profile)

Incredibly useful!

Manuel

Manuel (view profile)

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.

Muhammet

Rems

Rems (view profile)

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

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

Thanks,
John

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

Thanks,
John

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

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

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

Phillip (view profile)

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

Lucio

Lucio (view profile)

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.

Lucio

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

set(hh,'CData',realcolor);

Georg

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

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
--freezeColors(h)
generates an error.

Need to call:
--axes(h)
--freezeColors
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
--freezeColors(h)
generates an error.

Need to call:
--axes(h)
--freezeColors
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
--freezeColors(h)
generates an error.

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

Zhou

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

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

Vincent

thanks!

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

Andrew (view profile)

Carl

Carl (view profile)

Maria

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!

Maria

Eva

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.

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

Hassan Naseri

THANKS INDEEED

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

Sieun

Sieun (view profile)

olim

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.

Cheers
O

Fran

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.

Thanks.

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

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

Sophie

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]);
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:-(

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

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.

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.

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

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

Adam

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.

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)

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.

feili li

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

Nora

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:

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.

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?

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

Reyna (view profile)

Annette

Thanks!

David

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:

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

which worked fine for me!

David.

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

David (view profile)

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

Pearl

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)

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

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

[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

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.

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

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

Carlos

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

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

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

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

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

M C

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

Updates

1.3

Updating to reflect the possible obsolescense.

1.3

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

1.1

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