Search code examples
octave

How can I set the numbering of the x-axis of an Octave plot to engineering notation?


I made a very simple Octave script

a = [10e6, 11e6, 12e6];
b = [10, 11, 12];
plot(a, b, 'rd-')

which outputs the following graph.

Graph

Is it possible to set the numbering on the x-axis to engineering notation, rather than scientific, and have it display "10.5e+6, 11e+6, 11.5e+6" instead of "1.05e+7, 1.1e+7, 1.15+e7"?


Solution

  • While octave provides a 'short eng' formatting option, which does what you're asking for in terms of printing to the terminal, it does not appear to provide this functionality in plots or when formatting strings via sprintf.

    Therefore you'll have to find a way to do this by yourself, with some creative string processing of the initial xticks, and substituting the plot's ticklabels accordingly. Thankfully it's not that hard :)

    Using your example:

    a = [10e6, 11e6, 12e6];
    b = [10, 11, 12];
    plot(a, b, 'rd-')
    
    format short eng   % display stdout in engineering format
    
    TickLabels = disp( xticks )                                    % collect string as it would be displayed on the stdout
    TickLabels = strsplit( TickLabels )                            % tokenize at spaces
    TickLabels = TickLabels( 2 : end - 1 )                         % discard start and end empty tokens
    TickLabels = regexprep( TickLabels, '\.0+e', 'e' )             % remove purely zero decimals using a regular expression
    TickLabels = regexprep( TickLabels, '(\.[1-9]*)0+e', '$1e' )   % remove non-significant zeros in non-zero decimals using a regular expression
    
    xticklabels( TickLabels )   % set the new ticklabels to the plot
    
    format   % reset short eng format back to default, if necessary