Custom contour level labeling not working
5 views (last 30 days)
Show older comments
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';
0 Comments
Accepted Answer
Benjamin Kraus
on 4 Jun 2025
Edited: Benjamin Kraus
on 4 Jun 2025
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 Comments
Benjamin Kraus
on 4 Jun 2025
@Les Beckham: Good catch. That was just a mistake in my code. I've fixed it now.
More Answers (0)
See Also
Categories
Find more on Contour Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!