When displaying labels on contours Matlab doesn't allow you to control the format of the numbers, for example to change to scientific notation.
The individual text objects are normal text objects but how you get them is undocumented. You access them from the TextPrims
property of the contour handle.
figure
[X,Y]=meshgrid(0:100,0:100);
Z=(X+Y.^2)*1e10;
[C,h]=contour(X,Y,Z);
h.ShowText='on';
drawnow();
txt = get(h,'TextPrims');
v = str2double(get(txt,'String'));
for ii=1:length(v)
set(txt(ii),'String',sprintf('%0.3e',v(ii)))
end
Note: that you must add a drawnow
command to force Matlab to draw the contours, the number and location of the txt objects are only determined when the contours are actually drawn so the text objects are only created then.
The fact the txt objects are created when the contours are drawn means that they are recalculated everytime the plot is redrawn (for example figure resize). To manage this you need to listen to the undocumented event
MarkedClean
:
function customiseContour
figure
[X,Y]=meshgrid(0:100,0:100);
Z=(X+Y.^2)*1e10;
[C,h]=contour(X,Y,Z);
h.ShowText='on';
% add a listener and call your new format function
addlistener(h,'MarkedClean',@(a,b)ReFormatText(a))
end
function ReFormatText(h)
% get all the text items from the contour
t = get(h,'TextPrims');
for ii=1:length(t)
% get the current value (Matlab changes this back when it
% redraws the plot)
v = str2double(get(t(ii),'String'));
% Update with the format you want - scientific for example
set(t(ii),'String',sprintf('%0.3e',v));
end
end
Example tested using Matlab r2015b on Windows