Surf(x, y, z) with a colormap that is only two colours
14 views (last 30 days)
Show older comments
How can I use surf with a colormap that assigns a single colour (say red) to all negative values of z and another colour (say blue) to all the positive values of z. Looking at the simple code below, once it runs, you can grab the rotation tool and see the plot from above (see attached picture): how can I get only two colours in this top view, one red (for -ve values) and one blue for the +ve values? You can see I didn't even specify a colormap, so that Matlab goes to the default cmap. Any help? Thanks.
clear all
close all
x = linspace(-20,20,2400);
fz = exp(-x.^2./0.2).*cos(5.*x);
[X, Y] = meshgrid(x, x);
z = exp(-X.^2-Y.^2);
f = z.*meshgrid(fz,fz);
figure
surf(X, Y, f, 'LineStyle', 'None')
xlim([-5 5])
ylim([-5 5])
0 Comments
Accepted Answer
David Goodmanson
on 27 Sep 2020
Edited: David Goodmanson
on 27 Sep 2020
Hi Emil,
x = linspace(-20,20,2400);
fz = exp(-x.^2./0.2).*cos(5*x);
[X, Y] = meshgrid(x, x);
z = exp(-X.^2-Y.^2);
f = z.*meshgrid(fz,fz);
switch 2 % 1 or 2
case 1 % original question
figure(1)
surf(X, Y, sign(f), 'LineStyle', 'None')
colormap([1 0 0; 0 0 1]) % make a colormap with two choices
colorbar
case 2 % new question, not documented, see comments
figure(1)
surf(X, Y, f, 'LineStyle', 'None')
% pick a couple of rgb colors for the ends of the colorbar
c2 = [0 .8 .8] % top
c1 = [0 .3 .3] % bottom
% standard colormap has 64 gradations
map = [linspace(c1(1),c2(1),64)' ...
linspace(c1(2),c2(2),64)' ...
linspace(c1(3),c2(3),64)'];
colormap(map)
colorbar
end
xlim([-5 5])
ylim([-5 5])
xlabel('x')
ylabel('y')
zlabel('z')
view([0 0 1])
The result for swiich case 1 looks funny but I believe it is correct.
3 Comments
David Goodmanson
on 27 Sep 2020
Edited: David Goodmanson
on 27 Sep 2020
Hi emil,
see modified answer switch case 2 for a do-it-youself colorbar. Quite frankly for this particular example, since the gaussian function envelope drops off so quickly you are never going to see more than one oscillation. Also, in this example the function is near 0 most of the time. Therefore f~~0 dominates and gives the 'background' color. The background has to have 'bright colorness' to some extent because f~~0 is somewhere in the middle of the colorbar and there has to be room for f<0.
More Answers (1)
KSSV
on 27 Sep 2020
You can try something like this
x = linspace(-20,20,2400);
fz = exp(-x.^2./0.2).*cos(5.*x);
[X, Y] = meshgrid(x, x);
z = exp(-X.^2-Y.^2);
z(z>=0) = +1 ;
z(z<0) = -1 ;
f = z.*meshgrid(fz,fz);
%
figure
surf(X, Y, f, 'LineStyle', 'None')
xlim([-5 5])
ylim([-5 5])
See Also
Categories
Find more on Blue 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!