[Tex/LaTex] Box on pgfplot with X-axis at origin

pgfplotstikz-pgf

I am doing a plot where I want the X-axis positioned at the origin, which is accomplished with the code below:

\documentclass{article}
\usepackage{pgfplots}
\tikzset{>=latex}
\usetikzlibrary{plotmarks}
\pgfplotsset{grid style={dotted,gray}}
\pgfplotsset{compat=1.13}

\begin{document}
    \begin{tikzpicture}
        \begin{axis}[
        clip=false,
        xmin=0,
        xmax=20,
        axis x line = middle,
        grid=both]
            \addplot [domain=0:20,samples=200,red]{sin(deg(x))}; 
            \legend{$\sin(x)$}
        \end{axis}
    \end{tikzpicture}
\end{document}

Resulting in the plot seen below:

Now, as you can see, there are no horizontal borders at the top and bottom of the plot, which for other plots seem to be the default behaviour for pgfplots. I wonder if there is any way to get the horizontal borders (with or without tick marks …) back for a plot which has an X-axis aligned with the origin?

Best Answer

You can draw some additional lines at the beginning or at the end of the axis. For details have a look at the code.

\documentclass[border=2mm]{standalone}
\usepackage{pgfplots}
    \usetikzlibrary{plotmarks}
    \tikzset{>=latex}
    \pgfplotsset{
        compat=1.13,
        grid style={
            dotted,
            gray,
        },
    }
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
        xmin=0,
        xmax=20,
        axis x line=middle,
        grid=both,
        % add lines at the bottom and top of the axis as for `axis lines=box'
        % depending if `axis on top' is used, draw them at the beginning or
        % at the end
        execute at begin axis={
%        execute at end axis={
            \draw (rel axis cs:0,0) -- (rel axis cs:1,0)
                  (rel axis cs:0,1) -- (rel axis cs:1,1);
        },
    ]
        \addplot [domain=0:20,samples=200,red] {sin(deg(x))};
        \legend{$\sin(x)$}
    \end{axis}
\end{tikzpicture}
\end{document}

image showing the result of above code