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

27 ビュー (過去 30 日間)
qilin guo
qilin guo 2022 年 3 月 23 日
コメント済み: qilin guo 2022 年 3 月 23 日
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 件)

タグ

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by