[Tex/LaTex] Undefined control sequence on \frac

graphsmath-modepgfplots

I'd like to generate PDF's for some ad hoc screenshots, but I'm getting an undefined control error. I tried \usepackage{amsmath} after the line \usepackage{pgfplots} but that didn't work. I thought maybe that package was required for use of \frac{x}{2}

I'm using TeXworks with the following to try and generate a generic plot of x/2:

\documentclass{article}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}[>=stealth]
    \begin{axis}[
        xmin=-10,xmax=10,
        ymin=-10,ymax=10,
        axis x line=middle,
        axis y line=middle,
        axis line style=<->,
        xlabel={$x$},
        ylabel={$y$},
        ]
        \addplot[no marks,blue,<->] expression[domain=-10:10,samples=100]{\frac{x}{2}} 
                    node[pos=0.65,anchor=south west]{$y=\frac{x}{2}$}; 
    \end{axis}
\end{tikzpicture}
\end{document}

The error is on the node line 16 I believe, but I can't tell if it's syntax or otherwise.

! Undefined control sequence.
\pgfmath@dimen@ ...men@@ #1=0.0pt\relax \pgfmath@ 

l.16 ...=0.65,anchor=south west]{$y=\frac{x}{2}$};

Please consider me very new to LaTeX. I guess I'm assuming there is a missing package, since I can successfully plot simple linear graphs that don't include \frac.

Best Answer

You should write x/2 instead of \frac{x}{2}.

  • In the equation of the graph, you want a mathematical expression that PGFplots can understand. The syntax for division in PGFplots is simply /.
  • In the label for the graph, you just want a piece of text, so y=\frac{x}{2} is fine here.

Fixed code

\documentclass{article}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}[>=stealth]
    \begin{axis}[
        xmin=-10,xmax=10,
        ymin=-10,ymax=10,
        axis x line=middle,
        axis y line=middle,
        axis line style=<->,
        xlabel={$x$},
        ylabel={$y$},
        ]
        \addplot[no marks,blue,<->] expression[domain=-10:10,samples=100]{x/2} 
                    node[pos=0.65,anchor=south west]{$y=\frac{x}{2}$}; 
    \end{axis}
\end{tikzpicture}
\end{document}

enter image description here