How to properly color a surface in two different colours using surf function?

18 次查看(过去 30 天)
Dear MATLAB users,
I would like to color a surface in two different colours using surf function. I have a surface which is defined as . For f(x,y) <= 2, I want to use blue, while for f(x, y) > 2, red.
Here are my codes and the results. The fig. makes me satisfied when I am looking in MATLAB. But when I export my fig. to PDF-file, I find that the surface of f(x,y) <= 2 is plotted twice using two different colors (red and blue). I understant that it is normal but this is not I want.
clearvars; clc; close all; fclose all; format short; format compact;
x = linspace(-0.5, 0.5, 21);
[X, Y] = meshgrid(x, x);
Z = -2 * (cos(2*pi*X) + cos(2*pi*Y)) + 2;
Z1 = Z;
Z1(Z1 >= 2) = NaN;
fig = figure;
ax = axes;
hold on;
s1 = surf(ax, X, Y, Z);
s2 = surf(ax, X, Y, Z1);
set(s1, 'LineWidth', 0.5, 'EdgeColor', 'r', 'FaceColor', 'w');
set(s2, 'LineWidth', 0.5, 'EdgeColor', 'b', 'FaceColor', 'w');
camzoom(ax, 0.5);
view(ax, [120,30]);
set(ax, 'Box', 'on', 'PlotBoxAspectRatio', [1, 1, 1.5]);
hold off;
This is the exported PDF-file.
Also I tried to plot the two part of the surface (e.g., f(x, y) <=2 and f(x, y) > 2) separately, But I find the boundaries between the two parts is not connected smoothly. Please see the following codes and the results.
clearvars; clc; close all; fclose all; format short; format compact;
x = linspace(-0.5, 0.5, 21);
[X, Y] = meshgrid(x, x);
Z = -2 * (cos(2*pi*X) + cos(2*pi*Y)) + 2;
Z1 = Z;
Z2 = Z;
Z1(Z1 >= 2) = NaN;
Z2(Z2 < 2) = NaN;
fig = figure;
ax = axes;
hold on;
s1 = surf(ax, X, Y, Z2);
s2 = surf(ax, X, Y, Z1);
set(s1, 'LineWidth', 0.5, 'EdgeColor', 'r', 'FaceColor', 'w');
set(s2, 'LineWidth', 0.5, 'EdgeColor', 'b', 'FaceColor', 'w');
camzoom(ax, 0.5);
view(ax, [120,30]);
set(ax, 'Box', 'on', 'PlotBoxAspectRatio', [1, 1, 1.5]);
hold off;
Best regards,
Qilin.

采纳的回答

AndresVar
AndresVar 2022-3-23
编辑:AndresVar 2022-3-23
How about just 1 surface but you tweak the colormap
x = linspace(-0.5, 0.5, 21);
[X, Y] = meshgrid(x, x);
Z = -2 * (cos(2*pi*X) + cos(2*pi*Y)) + 2;
% color
C = Z;
C(Z<=2)=-1;
C(Z>2)=1;
% plot
fig=figure;
ax = axes;
s1 = surf(ax,X,Y,Z,C);
% color
s1.EdgeColor="interp";
s1.FaceColor='w';
s1.LineWidth=0.5;
BlueRedColormap = [0,0,1;1,0,0]; % just red and blue
colormap(fig,BlueRedColormap);
% pretty
view(ax,[120,30]);
set(ax,'Box', 'on', 'PlotBoxAspectRatio', [1, 1, 1.5]);
%saveas(gcf,'RedBlueSurf.pdf');

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Specifying Target for Graphics Output 的更多信息

标签

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by