[Tex/LaTex] Draw in pgfplot axis before axis and grid are drawn

pgfplotstikz-pgf

Is there a way to draw something using the axis coordinates (axis cs:x,y) before the axis and the grid are drawn?

Namely I would like to draw rectangles with tikz to give different areas of the plot different backgrounds, however, the only thing I found in the docs was before end axis which seems to be the earliest point in time when one can kick in with own tikz drawings having the axis cs available.

Best Answer

As Mark correctly states you could use the pgflayers. They provide just the tool!

However I would like to show you another way around the problem, which also could prove to ease the process since it is in axis coordinate system.

Basically what you need to know is that you can access the background style using the key: axis background. Once you have this you are capable of applying all the TiKz you want! We are lucky that the axis environment is computed before the background is drawn.

You should know that you have easy access to the current picture using the keys: path picture. By combining this with postaction or preaction you are pretty much home-safe! :)

What I have done here is to access the axis cs, followed by adding appropriate rectangles. You are pretty much free to do whatever you wish here. Add nodes, draw arbitrary things etc. However if you wish to annotate a certain point of interest, you are encouraged to do that by other means.

Notice however that the picture bounding box is not correct due to axis corrections, thus you should not use that.

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[axis background/.style={%
        postaction={ % Lets you draw after the background is drawn
            path picture={ % access the background picture
                \fill[opacity=0.5,blue] (axis cs:-5,0) rectangle (axis cs:-4,2e4);
                \fill[opacity=0.5,red] (axis cs:-5,2e4) rectangle (axis cs:-4,6e4);
                \fill[opacity=0.5,green] (axis cs:-4,.8e4) rectangle (axis cs:5,6e4);
            }
        },shade,top color=gray,bottom color=white
    },legend style={fill=white}]
    \addplot {exp(-2*x)};
    \addplot {exp(-2.2*x)};
    \legend{$e^{-x}$,$e^{-4x}$}
  \end{axis}
\end{tikzpicture}
\end{document}

Which produces:

output