MATLAB: How to label a contour plot in the same colors as the contour lines

contour label colorundocumented

I am hoping to create a contour plot with each line labeled in the same color as that line. I have found instructions for doing this in Python but cannot find the relevant code for matlab.
This is the code I found online (for Python I think): http://python4esac.github.io/plotting/matplotlib.html

Best Answer

There is no need to use Java, just to use the two hidden (undocumented/unsupported) properties TextPrims (the text label handles) and EdgePrims (the contour line handles), as shown below. For additional info on customizing the contour labels/lines/faces read https://undocumentedmatlab.com/blog/customizing-contour-plots
% Create a simple contour plot
x = -2:0.2:2;
y = -2:0.2:3;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2-Y.^2);
[C,hContour] = contour(X,Y,Z, 'ShowText','on');
% Update the text label colors
levels = hContour.LevelList;
labels = hContour.TextPrims; % undocumented/unsupported

lines = hContour.EdgePrims; % undocumented/unsupported
for idx = 1 : numel(labels)
labelValue = str2num(labels(idx).String);
lineIdx = find(abs(levels-labelValue)<3*eps, 1); %avoid FP errors using eps
labels(idx).ColorData = lines(lineIdx).ColorData;
end