How do I label a contour plot in the same colors as the contour lines?

조회 수: 5 (최근 30일)
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
  댓글 수: 2
Walter Roberson
Walter Roberson 2017년 10월 24일
There is a hint that this might perhaps be possible. The contour object, h, has a hidden property LabelTextProperties, that has a ColorData field that is maybe changeable to a color table. The problem with that is that because it is a hidden property, there is no good way to set the property.
The contour object has a java() method that allows you to dig into the java representation. That includes getting the children objects, which are various text and line objects and a couple of other things I have not explored. I have no yet found any way to change the color of the text objects (just of the line objects.)
Rik
Rik 2017년 10월 25일
I all else fails, you could just insert text objects with a white background. This would require a lot of manual labor to properly align and rotate, and would break the moment you decide to resize your plot. So really a last ditch effort.

댓글을 달려면 로그인하십시오.

채택된 답변

Yair Altman
Yair Altman 2017년 10월 25일
편집: Yair Altman 2017년 10월 25일
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
  댓글 수: 7
Warwick
Warwick 2017년 11월 11일
thank you. What I was after.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Alexandre
Alexandre 2023년 9월 20일
As of MATLAB R2023b we have introduced a new Property Input for LabelColor on Contour called 'flat', which will map Contour Label's Color to the colormap. This color mapping will be equivalent to the Line color mapping.
Please look at our updated documentation for more information:
Examples:
contour(peaks, 'LabelColor', 'flat')
contour(membrane, 'LabelColor', 'flat')
colormap abyss

카테고리

Help CenterFile Exchange에서 Contour Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by