Custom contour level labeling not working

조회 수: 4 (최근 30일)
Derik
Derik 2025년 6월 4일
댓글: Derik 2025년 6월 4일
I am trying to match my papers resutls with another and the way they label their contours is with a bit of an offset (screenshot of table). I m trying to find a way to be able to sort of overide the clabel so for a value of 0.5 for example it displays 1 as per the table in the paper. levels1 are my plotting lines and levels2 is what i want to use for labeling the lines. Doing it this way it just puts the labels at the "correct value levels"
levels1 = [-3 -2 -1 -0.5 0 0.5 1 2 3 4 5];
levels2 = [-4 -3 -2 -1 0 1 2 3 4 5 6];
% 1) Plot background (if you have one)
if Re == 400
bg = imread('comp.png');
else
bg = imread('Re_1000wcont.png');
end
bg = flipud(bg);
figure
imagesc([0 1],[0 1], bg);
set(gca,'YDir','normal');
hold on;
[C, hLine] = contour( ...
X, Y, -flipud(omega), ...
levels1, ...
'LineColor','b', 'LineStyle','--', 'LineWidth',1 );
axis equal; box on; xlim([0 1]); ylim([0 1]);
hold on;
clabel(C, hLine, levels2, ...
'FontSize', 13, ...
'LabelSpacing',300, ...
'Color', 'r');
xlabel('$x$', 'Interpreter','latex');
ylabel('$y$', 'Interpreter','latex');
ax = gca;
ax.TickLabelInterpreter = 'latex';

채택된 답변

Benjamin Kraus
Benjamin Kraus 2025년 6월 4일
편집: Benjamin Kraus 2025년 6월 4일
Assuming you are using MATLAB R2022b or newer, I would recommend leveraging the LabelFormat property, which lets you specify a custom function for generating your labels.
If you set the value of LabelFormat to a function handle, then the function is called with a vector containing all the levels. You can control the output, which should be a string vector of the same size. Whatever strings are returned are used as the labels on the lines.
I don't have your raw data, so I'll give an example with made-up data.
function labels = adjustValues(vals)
% Start by assuming each label will reflect the actual value.
labels = string(vals);
% Replace -0.5 and 0.5 with -1 and 1:
labels(vals == 0.5) = "1";
labels(vals == -0.5) = "-1";
% Replace -1 to -3 with -2 to -4.
labels(vals <= -1) = string(vals(vals <= -1)-1);
% Replace 1 to 5 with 2 to 6.
labels(vals >= 1) = string(vals(vals >= 1)+1);
end
[X,Y] = meshgrid(linspace(0,pi,50));
Z = (cos(X).*sin(Y))*6;
contour(Z, [-3:-1 -0.5 0 0.5 1:5], ShowText=true, LabelFormat=@adjustValues)
  댓글 수: 3
Benjamin Kraus
Benjamin Kraus 2025년 6월 4일
@Les Beckham: Good catch. That was just a mistake in my code. I've fixed it now.
Derik
Derik 2025년 6월 4일
Thank you so much this worked great!

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by