9

We can display tick labels as fractions by setting:

xticklabel style={/pgf/number format/frac}

However, how can we manually enter the tick points as fractions?

Just using xtick={0,2/3,1} does not work see, the MWE below.

 \documentclass{article}
 \usepackage{pgfplots}
 \pgfplotsset{width=9cm,compat=1.5}
 \begin{document}
 \begin{tikzpicture}
 \begin{axis}[
 xticklabel style={/pgf/number format/frac},
 domain=0:1,
 samples=9,
 xtick={0,2/3,1} ]
 \addplot { x };
 \end{axis}
 \end{tikzpicture}
 \end{document}
10

PGFPlots doesn't parse the expressions given in the xtick list. You can define your own key that does this and generates the list used for the tick labels.

Note that in order to get 2/3 to print correctly, you need to use /pgf/number format/frac shift=2 (or 1) to decrease the tolerance of the algorithm.

 \documentclass{article}
 \usepackage{pgfplots}
 \pgfplotsset{width=9cm,compat=1.5}

 \makeatletter
 \pgfplotsset{
    xtick parsed/.code={
        \c@pgf@counta 0\relax
        \foreach \x in {#1} {
            \pgfmathparse{\x}
            \ifnum\c@pgf@counta=0
                \xdef\pgfplots@xtick{\pgfmathresult}
            \else
                \xdef\pgfplots@xtick{\pgfplots@xtick,\pgfmathresult}
            \fi
            \global\advance\c@pgf@counta 1\relax
        }
    }
 } 
 \makeatother

 \begin{document}
 \begin{tikzpicture}
 \begin{axis}[
 xticklabel style={/pgf/number format/frac, /pgf/number format/frac shift=2},
 domain=0:1,
 samples=9,
 xtick parsed={0, 1/3, 2/3, 1}]
 \addplot { x };
 \end{axis}
 \end{tikzpicture}
 \end{document}
1
  • Is it possible to use \sfrac{1}{2} of package xfrac?
    – Hotschke
    Jun 11 '15 at 18:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.