Search code examples
matlabmatlab-figurecontour

Matlab: Format the decimals in contour labels


I want to cut the number of decimals in the following contour plot. I do:

[cc,hh] = contour(X,Y,Z,levels,'LineColor','k');hold on
texth = clabel(cc,hh,'FontSize',8);

which gets me the first contour with long labels. Then in order to cut the decimals I do:

for i = 1:size(texth); textstr=get(texth(i),'String'); textnum=str2double(textstr); textstrnew=sprintf('%0.0f', textnum) ; set(texth(i),'String',textstrnew); end

And this gives the second plot. As you see, there is a wide gap between the label and the contour lines which looks awful. Any ideas how to solve this?

enter image description here


Solution

  • Instead of modifying the result, create a contour plot with the levels you want, so you don't need to cheat the data.

    Define levels as e.g. levels=997:1010

    and then

    contour(X,Y,Z,levels,'LineColor','k','ShowText','on');
    

    Will create a contour plot with the text included and the levels being specifically the ones in the variable levels, in this case 997,998,999,...,1009,1010

    If, as @David suggests, your levels variable already is a vector, then replace it by round(levels) as himself suggested.