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

32 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

AndresVar
AndresVar am 23 Mär. 2022
Bearbeitet: AndresVar am 23 Mär. 2022
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 Kommentar
qilin guo
qilin guo am 23 Mär. 2022
Dear AndresVar, thank you very much! This is what I exactly want. You make it in an elegant way!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Specifying Target for Graphics Output finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by