How to properly color a surface in two different colours using surf function?
32 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
AndresVar
le 23 Mar 2022
Modifié(e) : AndresVar
le 23 Mar 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');
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Specifying Target for Graphics Output dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!