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.

  • 1
    You may want to look into pgflayers. You can probably put things behind the plot after it is drawn this way.
    – qubyte
    Jan 18, 2012 at 14:08

1 Answer 1


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.

  \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)};

Which produces:


  • Perfect! Exactly what I was looking for and explained very nicely! :)
    – barbaz
    Jan 18, 2012 at 14:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .