I have created a smooth color gradient 2-D contour plot with existing compiled data in Matlab. I have an x-axis, y-axis, and z-data contour plotted as a colormap. My goal is to
Thanks to @Cris Luengo for his comments directing me to contourc. Notice that contourc returns the isolines. According to the documentation,
To compute a single contour of level
k
, usecontourc(Z,[k k])
which implies we can identify specific values for the isolines (values of Z
) with
v = [.5 0.75 .85];
and then just use a loop to iteratively get the info needed using
for k = 1:length(v)
Ck = contourc(x,y,Z,[v(k) v(k)]);`
end
which allows us to pass the info to plot(...)
in the code below.
% MATLAB R2018b
x = 0:0.01:1;
y = 0:0.01:1;
[X,Y] = meshgrid(x,y);
Z = sqrt(X.^3+Y); % Placeholder
v = [.5 0.75 .85]; % Values of Z to plot isolines
figure, hold on
pcolor(X, Y, Z);
shading interp
colorbar
for k = 1:length(v)
Ck = contourc(x,y,Z,[v(k) v(k)]);
plot(Ck(1,2:end),Ck(2,2:end),'k-','LineWidth',2)
end
Old but works: Will delete once above answer finalized
Disclaimer: There may be an easier way to do this. See note at bottom.
x = 0:0.01:1;
y = 0:0.01:1;
[X,Y] = meshgrid(x,y);
Z = sqrt(X.^3+Y); % Placeholder
The plot command can overlay anything you want on top. Or you can use contourf and specify the contours marked, including highlighting individual contours. I've illustrated two approaches—I believe the one you're looking for uses hold on; plot(...)
as demonstrated below & with the left image.
In the left figure, you'll see I used logical indexing.
val = 0.75; % Value of Z to plot contour for
tol = .002; % numerical tolerance
idxZval = (Z <= val+tol) & (Z >= val-tol);
The success of this approach greatly depends on how fine the mesh is on Z
and on the required tolerance (tol
). If the Z-mesh is limited by data, then you'll have to adjust the tolerance and tune to your liking or to the limit of your data. I simply adjusted until I got the figure below and didn't tinker further.
% MATLAB 2018b
figure
subplot(1,2,1) % LEFT
pcolor(X, Y, Z); hold on
shading interp
xlabel('X')
ylabel('Y')
colorbar
val = 0.75; % Value of Z to plot contour for
tol = .002; % numerical tolerance
idxZval = (Z <= val+tol) & (Z >= val-tol);
plot(X(idxZval),Y(idxZval),'k-','LineWidth',2)
title('Bootleg approach for Z = 0.75')
subplot(1,2,2) % RIGHT
v =[0:.1:1.2] % values of Z to plot as contours
contourf(X,Y,Z,v)
colorbar
title('Contour plot specifying values v =[0:.1:1.2]')
Edit:
For future visitors, if the relationship between X
,Y
, and Z
is known, e.g. sqrt(X.^3 + Y) = Z
, then drawing a single curve for a particular Z
value may be extracted from that relationship (equation) directly by solving the equation. If it is based on data instead of an analytical formula, then that may be more difficult and the approach above may be easier (thanks to @Cris Luengo for pointing this out in the comments).