[Tex/LaTex] Graphing a sinusoidal function

tikz-pgf

I would like to plot the graph for y = |sin(pi*x)| on the interval -2.5 and 2.5. (The graph is on or above the x-axis, and both ends are at height 1.) TikZ plots a line through the origin. The label for the graph should be to the right end of the graph – it can extend past the x-axis. How to I add the label "x" to the x-axis and "y" to the y-axis?

\documentclass[10pt]{amsart}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}


\begin{document}

\hspace*{\fill}
\begin{tikzpicture}
\begin{axis}[width=4in,axis equal image,
          xmax=3,ymax=1.5,
          axis lines=middle,
          restrict y to domain=-1:2,
          enlargelimits,
          axis line style={shorten >=-0.25cm,shorten <=-0.25cm,latex-latex},
          ticklabel style={fill=white},
          extra x ticks={-2,-1,0,1,2},
          %extra x tick style={grid=none}
]

\addplot[domain=-2.5:2.5,mark=none,samples=200] {abs(sin(pi(x)))} node[fill=white, below left, yshift=-3pt]{$y=\vert\sin(\pi x)\vert$};


\end{axis}
\end{tikzpicture}
\hspace{\fill}

Best Answer

As noted by percusse, adding xlabel and ylabel to axis options solves the label issue.

Another issue is plotting the correct function, which is solved by modifying the formula in \addplot. Note that pgfplots natively operates on degrees, so a conversion from radians to degrees by deg() is needed. Also an explicit multiplication must be done: pi*x instead of pi(x).

Edit: Thanks to Jake for the comment that there is another way to use radians with pgfplots version 1.11 or later. Quoting the change log at http://pgfplots.sourceforge.net/:

  • new feature: 'trig format plots=rad' allows to use radians in trigonometric evaluations

So, if trig format plots=rad is added to axis options, deg() is no longer needed.

Example using deg()

output of example code

\documentclass[10pt]{amsart}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}

\begin{document}

\hspace*{\fill}
\begin{tikzpicture}
\begin{axis}[width=4in,axis equal image,
          xmax=3,ymax=1.5,
          axis lines=middle,
          enlargelimits,
          axis line style={shorten >=-0.25cm,shorten <=-0.25cm,latex-latex},
          ticklabel style={fill=white},
          extra x ticks={0},
          xlabel=$x$,ylabel=$y$,
          clip=false,
]

\addplot[domain=-2.5:2.5,mark=none,samples=200] {abs(sin(deg(pi*x)))} node[fill=white, right]{$y=\vert\sin(\pi x)\vert$};

\end{axis}
\end{tikzpicture}
\end{document}
Related Question