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

조회 수: 28 (최근 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');
  댓글 수: 1
qilin guo
qilin guo 2022년 3월 23일
Dear AndresVar, thank you very much! This is what I exactly want. You make it in an elegant way!

댓글을 달려면 로그인하십시오.

추가 답변 (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