# How to smoothen contourf plot to make it look better

6 views (last 30 days)
AARISH NAWAZ on 25 May 2022
Answered: DGM on 25 May 2022
I have X and Y data, X ranging from from 1 to 3 with step size 0.1 and Y from 1-3.5 with step size 0.1. Corresponding Z values for x,y combination are also available for each of these points. I have plotted a contour plot using contourf but it does not look smooth. How can i use spline function to smoothen the lines, or is there any other function which can help me smoothen these lines in the figure.

DGM on 25 May 2022
You need to use a finer mesh if you want the contour to appear smoother. This is complicated by the fact that all I have is a bunch of variables. I don't know how you created these or what they mean. If you could have done something to generate X,Y,Z with more resolution, that would be ideal. I'm going to assume that X,Y,Z are as given.
With that assumption, you can use interp2() to try to refine things. Again, this is complicated by the fact that it appears that you created X and Y by swapping outputs when using meshgrid(), so X is a Y grid and Y is a X grid. Accordingly, I'm going to do the interpolation with the axes swapped.
% original contour
contourf(X,Y,Z) % pick some new resolution
npoints = [100 100]; % [x y]
% your x and y look like they were swapped when using meshgrid()
Xfine = linspace(1,3,npoints(1));
Yfine = linspace(1,3.5,npoints(2)).';
[Xfine Yfine] = meshgrid(Xfine,Yfine);
Zfine = interp2(Y,X,Z,Yfine,Xfine,'cubic');
% fine contour
clf
contourf(Xfine,Yfine,Zfine) ### More Answers (1)

Bjorn Gustavsson on 25 May 2022
Best way (probably) to go about making your contourlines smoother is to interpolate your data:
Xi = linspace(min(X(:)),max(X(:)),20*size(X,2));
Yi = linspace(min(Y(:)),max(Y(:)),20*size(Y,1));
Zi = interp2(X.',Y.',Z.',Xi,Yi(:),'cubic');
subplot(2,2,3)
subplot(2,2,4)
contourf(Xi,Yi,Zi)
This is one way to proceed.
One point to mention is that your X and Y arrays aren't using the standard matlab-notation with the X-array with elements varying along the second dimension - that will trip you up at times.
HTH

R2022a

### Community Treasure Hunt

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

Start Hunting!