Search code examples
matlabmatlab-figure

MATLAB contour sharp corners


MATLAB contour plots appear to round corners, even when they should not be rounded.

In the plot

num_incs = 1000;
x = linspace(-1,1,num_incs);
[Xa,Ya] = meshgrid(x,x);
Z = abs(Xa) + abs(Ya);

contour(Xa,Ya,Z,20,'LineWidth',4);

one-norm plot

the corners are rounded. Is there a way to turn off automatic rounding in order to make the corners "sharp"?

I've tried changing the renderer, but to no affect. Also, turning off graphics smoothing with

set(gcf,'GraphicsSmoothing','off'); does not produce sharp corners.

EDIT: Note that on Matlab 2020b with num_incs = 1001 (or 3), I still get rounded corners: enter image description here

EDIT 2: I'm trying to access and modify the LineJoin property:

num_incs = 3;
x = linspace(-1,1,num_incs);
[Xa,Ya] = meshgrid(x,x);
Z = abs(Xa) + abs(Ya);

[C,hContour] = contour(Xa,Ya,Z,20,'LineWidth',4);

drawnow;
for i = 1:length(hContour.EdgePrims)
    hContour.EdgePrims(i).LineJoin = deal('miter');
    hContour.EdgePrims(i).LineWidth = 1; % to see what is being adjusted
end

but this only affects the "outer" lines. This approach was inspired by this post.

Conclusion:

https://stackoverflow.com/a/68533356/3385432


Solution

  • You can set the LineJoin property of the lines to 'miter' to get sharp corners:

    [C,h] = contour(Xa,Ya,Z,20, 'LineWidth',4);
    draw now
    set(h.EdgePrims,'LineJoin','miter')
    

    By default this property is 'round'.

    But be aware that the sharp corners produced can be unreasonably long, depending on the angle between the two lines meeting, and leading to misinterpretation of the data. A third option is 'chamfer', which gives sharp corners but cuts them off if they become too large.