[Tex/LaTex] Shading a Region Between Two Dashed Lines

tikz-pgf

I have drawn an axis with two dashed vertical lines:

    \begin{tikzpicture}
\begin{axis}[
    axis x line=middle, 
    axis y line=middle, 
    ymin=-6, ymax=6, ytick={1,3,5,-1,-3,-5}, ylabel=$y$, 
    xmin=-2.3, xmax=2.3, xtick={-1,-2,1,2}, xlabel=$x$
    ]
    \pgfplotsinvokeforeach{-1, 1}{
      \draw[dashed,color=red] ({rel axis cs: 0,0} -| {axis cs: #1, 0}) -- ({rel axis cs: 0,1} -| {axis cs: #1, 0});};
     \addplot[red, mark=*] coordinates {(1,1)};
     \addplot[red, mark=*] coordinates {(-1,1)};
\end{axis}
\end{tikzpicture}

I would like to shade the region between the dashed lines.

Best Answer

Here's another possibility (different from what has been suggested in comments) using \closedcycle; the axis on top=true option causes the axis to be typeset on top of the filling:

\documentclass{article}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
    axis on top=true,
    axis x line=middle, 
    axis y line=middle, 
    ymin=-6, ymax=6, ytick={1,3,5,-1,-3,-5}, ylabel=$y$, 
    xmin=-2.3, xmax=2.3, xtick={-1,-2,1,2}, xlabel=$x$
    ]
\addplot[fill=cyan,domain=-1:1,draw=none] {6} \closedcycle;
\addplot[fill=cyan,domain=-1:1,draw=none] {-6} \closedcycle;
    \pgfplotsinvokeforeach{-1, 1}{
      \draw[dashed,color=red] ({rel axis cs: 0,0} -| {axis cs: #1, 0}) -- ({rel axis cs: 0,1} -| {axis cs: #1, 0});};
     \addplot[red, mark=*] coordinates {(1,1)};
     \addplot[red, mark=*] coordinates {(-1,1)};
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

Related Question