PGFPlots – How to Format Significant Figures in TikZ

formattinggraphspgfplotstikz-pgf

I'm trying to work out how to change the number of sig figs in the axis labels. I.e., I want the graph to display 0.0, 1.0, etc. Any ideas?

\documentclass{memoir}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}

\begin{document}
\begin{tikzpicture}
% horizontal axis
\begin{axis}[xmin=0,xmax=50,ymin=0.0,ymax=4.0,grid=both,minor tick num=4, 
    major tick length=0pt,
    minor tick length=0pt,
    %no markers,
    ylabel=Applied Force/N,
    xlabel=Length/cm,
 every major grid/.style={black,opacity=0.8}]

 \addplot [black] coordinates  {
(0,0)
(8,0)
(38,3)};
 \end{axis}
\end{tikzpicture}

\end{document}

Best Answer

You can accomplish this by adjusting the style of whichever axis' tick labels you wish to adjust (xticklabel style, yticklabel style, or ticklabel style for both axes). Here I assume you wish to modify the y-axis tick labels.

The particular items of interest are

  • /pgf/number format/fixed zerofill (fixed format with trailing zeros shown) and
  • /pgf/number format/precision=1 (display one digit after the decimal separator).

Since these are both in the same "folder", we can save keystrokes by using .cd to switch into that folder.

Putting this all together, we have

yticklabel style={/pgf/number format/.cd,fixed zerofill,precision=1}

which can be added to the axis environment options.

Complete Code

\documentclass{memoir}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}

\begin{document}
\begin{tikzpicture}
% horizontal axis
\begin{axis}[xmin=0,xmax=50,ymin=0.0,ymax=4.0,grid=both,minor tick num=4, 
    major tick length=0pt,
    minor tick length=0pt,
    %no markers,
    ylabel=Applied Force/N,
    xlabel=Length/cm,
    yticklabel style={/pgf/number format/.cd,fixed zerofill,precision=1},
    every major grid/.style={black,opacity=0.8},
]

 \addplot [black] coordinates  {
(0,0)
(8,0)
(38,3)};
 \end{axis}
\end{tikzpicture}

\end{document}

Output

enter image description here