How to set black color for zero (or nan) values in surf and contourf plots?
14 views (last 30 days)
Show older comments
I want to use surf plot such that all negative and zero values should be plotted in black by using autumn colormap.
I'm trying to replace negative values with nan and by adding [0 0 0] to the colormap, but this doesn't work exactly.
Maybe the solution is merge 2 surf plot...
How can I obtain this?
0 Comments
Answers (1)
Cris LaPierre
on 2 May 2025
Edited: Cris LaPierre
on 2 May 2025
First, the autumn colormap does not contain black, so you will need to do some coding for this to happen.
Additionally, nan values are ignored when creating a surf plot. You will need to give them a value in order to plot them.
Let's start by looking at what the plot looks like already.
% Create some data that contains missing and NaN values
[X,Y,Z] = peaks(25);
Z(Z<-4) = nan;
% view a surf plot of the original data
surf(X,Y,Z,'FaceColor','interp')
C = colormap('autumn');
colorbar
The caxis function let's you set the colormap images, which affects what values map to what colors. Everything below the lower limit is mapped to the first color. So one approach would be to create a custom colormap where the first color is black and the rest of the colors are from the autumn colormap.
C = [0,0,0;C];
You also need to assign a value to the NaN entries in order for them to be displayed. For them to be black, they must have a value less than or equal to the lower caxis limit. There are seveal fill methods available, so look at the doc page for what makes the most sense for your data.
Z = fillmissing(Z,'pchip');
Now plot the updated data, apply the custom colormap, and set the color limits.
figure
surf(X,Y,Z,'FaceColor','interp')
colormap(C)
caxis([0,inf])
colorbar
3 Comments
Cris LaPierre
on 4 May 2025
"The contourf function uses the current colormap to fill the spaces between the levels in the plot. The first color fills the space between the lowest level and the level above it. The last color corresponds to Z-values that are greater than the highest level in the plot. If Z contains values that are smaller than the lowest level displayed in the plot, the region between the lowest level and the smallest Z-value is white."
Here again, NaN values are not drawn, so you'll want to replace those with a value that corresponds to the color you want. Assuming that is black again, I set them equal to 0 here.
To ensure you get the behavior you want, specify the levels. Here, that could be [-inf 0:7].
% Create some data that contains missing and NaN values
[X,Y,Z] = peaks(25);
Z(Z<0) = 0;
% Create custom colormap
C = colormap('autumn');
C = [0,0,0;C];
% view a surf plot of the original data
contourf(X,Y,Z)
colormap(C)
caxis([0,inf])
colorbar
See Also
Categories
Find more on Color and Styling in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


