Why does the legend of my contour plot not match the color of my contour lines in MATLAB 7.0 (R14)?

5 views (last 30 days)
I am plotting contours and setting the line colors for the contour lines manually. When I add a legend, the legend refers to colors from the figure's colormap and ignores the colors of the lines on the contour plot. The same code works in MATLAB 6.5 (R13).
The following code can reproduce the error:
figure;
z = [2 4 6 8 0 0 0 0 0 0; ...
2 4 6 8 10 0 0 0 0 0; ...
2 4 6 8 10 12 14 0 0 0; ...
2 4 6 8 10 12 14 16 18 0; ...
2 4 6 8 10 12 14 16 18 20; ...
2 4 6 8 10 12 14 16 18 20; ...
2 4 6 8 10 12 14 16 18 20];
hold on;
a1 = contour(z, [4 4], 'k');
a2 = contour(z, [6 6], 'r');
a3 = contour(z, [8 8], 'g');
a4 = contour(z, [10 10], 'b');
legend('4', '6', '8', '10');

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
This bug has been fixed for Release 14 SP1 (R14SP1). For previous releases, read below for any possible workarounds:
This is a bug in MATLAB 7.0 (R14) in the way that MATLAB handles contour plots.
To work around this issue, instead of manually specifying colors of the contour lines, use the COLORMAP command to set the colormap before plotting, and then plot the contours one at a time according to the colormap. The legend will then match the contour colors.
figure;
z = [2 4 6 8 0 0 0 0 0 0; ...
2 4 6 8 10 0 0 0 0 0; ...
2 4 6 8 10 12 14 0 0 0; ...
2 4 6 8 10 12 14 16 18 0; ...
2 4 6 8 10 12 14 16 18 20; ...
2 4 6 8 10 12 14 16 18 20; ...
2 4 6 8 10 12 14 16 18 20];
hold on;
map = [0 0 0; 1 0 0; 0 1 0; 0 0 1];
colormap(map);
% Plot each contour individually;
% To draw a single contour of level i, use contour(Z,[i i])
a1 = contour(z, [4 4]);
a2 = contour(z, [6 6]);
a3 = contour(z, [8 8]);
a4 = contour(z, [10 10]);
legend('4', '6', '8', '10');

More Answers (0)

Categories

Find more on Contour Plots in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!