File Exchange

image thumbnail

contourfcmap: filled contour plot with precise colormap

version (484 KB) by Kelly Kearney
Creates a filled contour plot, with more precise control over colors than contourf.


Updated 22 Jun 2018

From GitHub

View Version History

View license on GitHub

Create a filled contour plot in Matlab, with better color-to-value clarity. See full description, along with examples, at

Cite As

Kelly Kearney (2021). contourfcmap: filled contour plot with precise colormap (, GitHub. Retrieved .

Comments and Ratings (44)

Maxime Marin

Great code.
@Pablo Poulain The error stems from line 94 in pcolorbar.m:

tk = linspace(0,1,nblock+1); -> tk = linspace(0,1,nblock+1)';
This will fix the error.

Kenneth Johnson

Perfect! Thank you.

Pablo Poulain

Hello, I love the code it is worrking as expected. However ihave a small problem with the displaying of all color levels evenly on the colorbar, regardless of value, as it seems not to work when i try to run the example.
Here is the error code (i'm on matlab R2018a) :

Error using patch
Vectors must be the same length.

Error in pcolorbar (line 122)
h.p = patch(xpatch, ypatch, cpatch);

Error in contourfcmap (line 323)
hout.cb = pcolorbar(clevcbar, cmapcbar, 'even', Opt.evencb, 'location', Opt.cbarloc);

If you can find a way around it would be great because i don't understand why the code is not working.

Thanks a lot

beijia qin

i've solved that, thanks again

beijia qin

Thanks for sharing, it's exactly what i need.
One problem please, is it possible if I want to remove all the lines? i Just want the color.

Thanmay Sunil Menon

Fabrizio Gabbiani

Thanks, Kelly. I downloaded the updated version this morning and the 'calccontour' option now works with R2018a. Using the option solves all the Questions that I raised below. Cheers, Fabrizio

Kelly Kearney

@Fabrizio Gabbiani,

Question 1: Oops, I seem to have missed one call to poly2cw when I rewrote the function for polyshape objects. I've now corrected that, and just pushed an update (should show up on the FEX within a day). Please let me know if you still encounter errors with the newer version!
Question 2.1: The lack of red you see in the bottom portion is due to what I refer to as the "unenclosed lower-than-lowest-contour region" bug in contour. The contour function doesn't draw these, for some reason, so the recolor method inherits that bug. The calccontour method should properly color that lowest region. For more info, see the algorithms section of the README.
Question 2.2: With the recolor method, no, I don't think there's a way around the un-recoloring. With each new release of Matlab, the contour objects seem to get more and more resistant any tampering. Very frustrating. But calccontour should be fine...
Question 2.3-2.5: I believe you're just referring to the stacking of objects here? If you want the X lines on top of the Z contours, I think just calling contour second (with a hold on before it) should work.

contourfcmap(X,Y,Z,[3 4]',[1 1 0],'lo',[1 0 0],'method','calccontour');
hold on;

Fabrizio Gabbiani

Hi Kelly, my second question is related to the following code, which looks at interactions between contourfcmap and contour.

x = -2:0.1:2; y = -1:0.1:3; [X,Y] = meshgrid(x,y); Z = X.^2+Y.^2;
figure; contourfcmap(X,Y,Z,[3 4]',[1 1 0],'lo',[1 0 0]); %question 1
contour(X,Y,X); %question 2

figure; contour(X,Y,X);
contourfcmap(X,Y,Z,[3 4]',[1 1 0],'lo',[1 0 0]); %question 3
contour(X,Y,X); %question 4

%Question 1: why is the central region not colored in red since it is
%lower than the first contour line (clear if one looks at Z<3)?
%Question 2: is there a way to avoid the change in colors for the fill?
%Question 3: At this point the lines are not shown in the yellow region,
%can this be changed?
%Question 5: this is (almost, see Q1) what I want: yellow regions and lines over
%the whole plot, is there a way to get this without calling contour twice?

Thanks for any insight you might have, Fabrizio

Fabrizio Gabbiani

Thank you for the prompt response. I have two additional questions. Let me formulate the 1st one (2nd tomorrow): I tried to use the 'calccontour' version today after downloading from this page and got an error message that poly2cw requires the Mapping Toolbox. I have Matlab R2018a. Did I miss something? Thanks in advance for any suggestion, Fabrizio.

Kelly Kearney

@Fabrizio Gabbiani,

Yes, the "calccontour" method renders the contours as patches, so you can change their transparency via the 'FaceAlpha' attribute of the patches. And the most recent version of the code no longer requires the Mapping Toolbox, assuming you have R2017b or later (for older versions, Mapping Toolbox is unfortunately still required).

Fabrizio Gabbiani

Fabrizio Gabbiani

Hi Kelly, one question about the package: is it possible to make the filled contours transparent? It does not seem to be possible with the standard version 'recolor'. How about the 'calccontour' version? I don't have the mapping toolbox, but wanted to know if it would solve the issue. Thanks, Fabrizio

Kelly Kearney

@Nick Lybarger, Thanks for pointing out this bug; it seems to be one I introduced in my recent overhaul of the function. I just pushed a new release; if you still encounter this error, please open a new issue on the Github page and I'll look into it.

Nick Lybarger

I know this hasn't been tested with R2016b, but I figured I'd post anyway. This function is great, and I really can't understand why Matlab doesn't have this sort of functionality natively.

In R2016b, however, the colorbar doesn't seem to behave as simply as indicated in the description. When I run the function as:
the filled contours are plotting correctly using the colormap I indicate, but no colorbar appears. Has anyone else had this problem?

Kelly Kearney

@timo kropp: The exact method for hiding the contour lines depends on your version of Matlab and the contour-coloring method you use. Assuming a recent version, with the 'calccontour' method, you can hide or delete the lines using the contour line handles returned from this function:

h = contourfcmap(x,y,z,clev,cmap, 'method', 'calccontour');
set(h.l, 'visible', 'off'); % Hide...
delete(h.l); % ... or delete

If you use the recolor option, the lines are part of the contourgroup object, so you can't delete them without deleting the whole object. But you can hide them:

h = contourfcmap(x,y,z,clev,cmap, 'method', 'recolor');
h.h.LineColor = 'none';

timo kropp

timo kropp

How can i delete the contour lines?

Kelly Kearney

@Tae Lim,

The poly2cw function is part of the Mapping Toolbox; as mentioned in the help, you need this toolbox in order to run the 'calccontour' option of this function.

Tae Lim

Thank you for sharing a great code. I encountered an error when I ran your example. Below is the error code I got:

Undefined function 'poly2cw' for input arguments of type 'cell'.

Error in contourfcmap (line 613)
[xc,yc] = poly2cw({S.X}, {S.Y});

I am running Matlab R2016b on window 10. Thank you!

Kelly Kearney

@Peter Hristov

Thanks for pointing out this bug; I think I've now corrected things to properly deal with single-contour plots, both pre- and post-R2014b. New version just pushed to Github.

Peter Hristov

@Kelly Kearney Great function (as seen by rating). There is however a simple bug. Line 368 in contourfcmap.m assumes that the shaded patch will have more than one child and attempts to convert their handles from a cell array to a matrix. This is not always the case, so maybe you could add a simple if to check the number of children and act accordingly. Thanks!

Peter Hristov

Kelly Kearney


Thanks for pointing that out; new version just uploaded that should fix that error for pre-2011b releases.

Greg King

This function is just what I need, but it reports an error when I run it using ...
MATLAB Version (R2010b)
on mac osx.

The error is that caused by a call to narginchk, which is not in the R2010 release.

Kelly Kearney


No, I haven't tested this in 2016b yet. If you ask because you've found an incompatibility, please follow the GitHub link (upper right) and enter it as an issue.


Is there a version of this that works for MATLAB R2016b?


I frequently find this submission of yours to be tremendously useful. I often have a suite of plots or a panel of subplots and this script is the only way I can get consistency of colouring throughout.

Meanwhile some other users may find the following tweak helpful (it took me a while to twig) - To get rid of the actual contour lines, use h.h.LineColor = 'none'.

I'd rate the script at 5 but I've already done earlier this year.

Kelly Kearney


Tracked that bug to line 211, where meshgrid-style input was being incorrectly classified as a vector (and therefore x/y weren't converted to vectors as they should be). Now fixed.

Kyle Wang

Found a possible bug at Line #468 in contourfcmap.m.

The code
F = griddedInterpolant({x,y},z');
shall be corrected as
F = griddedInterpolant(x',y',z');

Otherwise the built-in example won't run.

Kelly Kearney


Thanks for pointing out this shortfall. I've modified the code so it now mostly supports irregular data grids (there are some edge cases involving NaNs that don't work so well, but most contourf-friendly data should be fine).


In CONTOURF, "If X or Y [matrices] is irregularly spaced, then contourf calculates contours using a regularly spaced contour grid, and then transforms the data to X or Y."

Contourfcmap works fine when I try it with regular X and Y matrices, but not with Y as an irregular one. When I attempt to do so, then Contourfcmap returns this error messsage - 'Error using interp2>makegriddedinterp (line 237)
Input grid is not a valid MESHGRID.

Error in interp2 (line 136)
F = makegriddedinterp(X, Y, V, method,extrap);

Error in contourfcmap (line 389)
tmp = interp2(x,y,z,xyz{ii}(1,:), xyz{ii}(2,:));".

Is it possible to incorporate the capability for irregular Y matrix into contourfcmap? I have the feeling it might be a ridiculously massive amount of work.
Nevertheless, for regular grids, I find your function gives the desired superior graphic. So, thank you.

Kelly Kearney


You're right... I recently updated the code to support NaNs in the data and didn't thoroughly test the new bit for older versions of Matlab. Just added a fix for that.

ed zaron

Hi Kelly,

I just downloaded and tried out this package but received this error when I tried the basic demo:
contourfcmap(x,y,z,[-5 -3 -2:.5:2 35],jet(12),[.8 .8 .8], [.2 .2 .2], 'eastoutside')
[x,y] = meshgrid(linspace(0,1,100));

Undefined function or variable "isn".

Error in contourfcmap (line 344)
elseif isn(ip)

I am running R2012b ( 64-bit (glnxa64).

The concept of the package looks great; I'm sure it is a version incompatibility or typo in the latest update.

All the best,


Kelly Kearney


Your x, y, and z data need to formatted in the same way as for the native contourf function, so you'll need to grid your data (not knowing the arrangement of the points in your vectors, I don't know whether you'd have to simply reshape, regrid, or use a scattered interpolant). Type help contourfcmap to see an example of use.


hello ,
I have a matriz of 3 colums (x,y,z), how I should use the code to run the program. what of the three files I must to run firts
thanks a lot!


Superb function, thanks.


exactly what I needed


great submission, thanks a lot

Kelly Kearney

@Earle Wilson,

Both saturated low and high values should be colored by the colors defined by the 'lo' and 'hi' inputs, respectively; by default these are white, but you can set them to be the same as the first and last cmap values if you want a saturated effect. If you see a different result please send me an example and I'll look into it.

Earle Wilson

great function! This saved me many hours of working around all the bugs in contourf.

The only (minor) short coming is that this function doesn't deal with saturated low values. Eg. if you enter:
and there are values in z < min(clev), they will be plotted as white spaces. This is an issue with contourf really, which I won't get into here. An easy fix is set all values in z outside the clev limits to min(clev) or max(clev). Eg.
toohigh = z>max(clev); z(toohigh) = max(clev);
loolow = z<min(clev); z(toolow) = min(clev);

Kelly Kearney

Added minmax subfunction into main code (overlooked this dependency on a simple helper function in previous upload). Thanks, Karin and Aurelien, for pointing out that mistake.

Aurelien Queffurust

I wanted to test your code but:
the minmax function which is required by your code is not shipped .

Another remark:
You have forgotten a bracket in the given example in the header of M-file:
[x,y] = meshgrid(linspace(0,1,100)
should be:
[x,y] = meshgrid(linspace(0,1,100))

Now waiting for minmax.m before rating.



Tjaart de Wit

Great function! Thanks

MATLAB Release Compatibility
Created with R2010a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!