User1961
User1961

Reputation: 131

MATLAB how to plot contour with special LineWidth for certain value

I have the following script:

close all; clear all; clc;

x = linspace(-2*pi,2*pi);

y = linspace(0,4*pi);

[X,Y] = meshgrid(x,y);

Z = sin(X)+cos(Y);

values = -10:0.5:10;

figure

[C,hh] = contour(X, Y, Z, values,'r', 'LineWidth',1); 

clabel(C, hh, values, 'fontsize',7)

As you can see in the contour lines, all of the lines are plotted with LineWidth = 1. I would like to plot special line for the value = 0, with LineWidth = 2, how to set it? Thanks a lor for your help.

Upvotes: 1

Views: 2564

Answers (1)

sco1
sco1

Reputation: 12214

You will need to make a secondary contour plot to highlight the desired contour levels. The MathWorks has an example of this in the documentation.

For your case we'll have something like the following:

% Generate sample data
x = linspace(-2*pi,2*pi);
y = linspace(0,4*pi);
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);
values = -10:0.5:10;

% Generate initial contour plot
figure
[C,hh] = contour(X, Y, Z, values,'r', 'LineWidth',1); 
clabel(C, hh, values, 'fontsize',7)

% Generate second contour plot with desired contour level highlighted
hold on
contour(X, Y, Z, [0 0], 'b', 'LineWidth', 2); 
hold off

Which returns the following:

yay

Not that I've specified the single contour level as a vector. This is explained by the documentation for contour:

contour(Z,v) draws a contour plot of matrix Z with contour lines at the data values specified in the monotonically increasing vector v. To display a single contour line at a particular value, define v as a two-element vector with both elements equal to the desired contour level. For example, to draw contour lines at level k, use contour(Z,[k k])

If you want to highlight multiple levels then this does not apply (e.g. contour(X, Y, Z, [-1 0], 'b', 'LineWidth', 2) to highlight -1 and 0)

Upvotes: 2

Related Questions