[Tex/LaTex] draw grid in pgfplots when axis line=none

pgfplots

I would like to have a grid in the y axis although the axis y line is not drawn, either by setting axis y line=none or hide y axis. In the MWE below the horizontal line along y=0 is not drawn when I use the extra y ticks method described in one of the answers here. How could it work when the y axis is not displayed?

\documentclass{standalone}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    extra y ticks       = 0,
    extra y tick style  = { grid = major },
    domain=0:360,
    hide y axis,
    ]
    \addplot {sin(x)};
  \end{axis}
\end{tikzpicture}
\end{document}

Best Answer

The key hide y axis completely disables all ticks and lines, extra or otherwise. Instead, you can stop the axis line from being drawn by setting

separate axis lines,
y axis line style= { draw opacity=0 }

The separate axis lines is necessary to be able to assign the line style only to the y axis, since usually the axes are drawn with a single path. Note that you have to use draw opacity=0 to hide the y axis, the usual approach draw=none doesn't work here.

\documentclass{standalone}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    domain=0:360,
    ytick=0,
    separate axis lines,
    y axis line style= { draw opacity=0 },
    ymajorgrids,
    tick pos = left
    ]
    \addplot {sin(x)};
  \end{axis}
\end{tikzpicture}
\end{document}

In case you want to do away with the tick mark and the tick label, the easiest thing might be to use one of the approaches from How can I add a zero line to a plot? to draw the zero line without the tick/grid mechanism.

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    domain=0:360,
    hide y axis,
    before end axis/.code={
      \draw [/pgfplots/every axis grid] ({rel axis cs:0,0}|-{axis cs:0,0}) -- ({rel axis cs:1,0}|-{axis cs:0,0});
    },
    axis lines*=left
    ]
    \addplot {sin(x)};

  \end{axis}
\end{tikzpicture}
\end{document}