2
votes

I have a matlab script such as this:

x = linspace(-2*pi,2*pi);
y = linspace(0,4*pi);
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);
Z1 = cos(.5*X) + sin(2*Y);

figure
[c h] = contour(X,Y,Z, '-r')  
hold on
[c1 h2] = contour(X,Y,Z1, '-b')
legend('test1', 'test2')

I have two contour plots on the same plot, one shown in red, the other shown in blue. The problem is that the legend doesn't show up in the red and blue colors. In an older version of matlab this worked just fine, but how are you supposed to define the legend in R2014b so that it has red contours next to 'test 1' and blue contours next to 'test 2'?

Someone else had a very similar question on mathcentral but it didn't get answered: http://www.mathworks.com/matlabcentral/answers/164210-how-does-the-contour-plot-with-r2014b-work.

Thanks!

1
Have you looked at clegendm ? - Ratbert

1 Answers

1
votes

According to the documentation, in R2014b "Colorbar and legend have new properties and do not support some axes properties". As the handle returned by contour is now a Contour object, there is little you can do.

Still, to get the desired behavior you have this awfully ugly hack:

x = linspace(-2*pi,2*pi);
y = linspace(0,4*pi);
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);
Z1 = cos(.5*X) + sin(2*Y);

figure
hold on

[~, h1] = contour(X,Y,Z, '-r');
h1_ = plot(NaN, '-r');
[~, h2] = contour(X,Y,Z1, '-b');
h2_ = plot(NaN, '-b');

L = legend([h1_ h2_], 'test 1', 'test 2');