3
votes

Consider the following MWE to create a contour plot:

close all
[X,Y]=meshgrid(0:100,0:100);
Z=(X+Y.^2)*1e10;
[C,h]=contour(X,Y,Z);
h.ShowText='on';

However, the labels always show a full integer notation of the contours. Is there a reasonable way to change this behaviour? (say, comparable to how MATLAB displays variables in the command window, or a forced scientific notation)

enter image description here

1

1 Answers

7
votes

You can do this using the undocumented MarkedClean event.

Unfortunately Matlab updates the text everytime the plot is redrawn (e.g. figure resize) - so you need to add a listener to update them each time that happens - hence why you listen for this particualr event.

function test
  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