I'm drawing a fairly complex picture with many overlapping areas. Is there a way to pass each \draw snippet to a layer specified in the options? Or even better, based on its axis position?
I know of the backgrounds library but only offers two layers. In the manual section 108.3 (pg. 1080) pgfonlayer is introduced. That would meet my needs but it requires encapsulating each command (or block of commands) with a begin{pgfonlayer}{<layer>}…\end{pgfonlayer} so that is cumbersome and reduces readibility. I want something like \draw[layer=<layer>], in the way the backgrounds library does. How would I go about achieving that?
A small MWE to illustrate:
\documentclass[tikz,border=10pt]{standalone}
\begin{document}
\pgfdeclarelayer{backlayer}
\pgfdeclarelayer{backlayer2}
\pgfdeclarelayer{frontlayer}
\pgfsetlayers{backlayer,backlayer2,main,frontlayer}
\begin{tikzpicture}
\begin{scope}[xshift=-5cm]
\draw (0,0) rectangle (2,2);
\fill[red] (1,1) rectangle (3,3);
\fill[blue] (-1,-1) rectangle (1.5,1.5);
\fill[green] (0,0) circle (1.5);
\end{scope}
%with layers
\begin{pgfonlayer}{frontlayer}
\draw (0,0) rectangle (2,2);
\end{pgfonlayer}
\begin{pgfonlayer}{backlayer}
\fill[red] (1,1) rectangle (3,3);
\end{pgfonlayer}
\begin{pgfonlayer}{main}
\fill[blue] (-1,-1) rectangle (1.5,1.5);
\end{pgfonlayer}
\begin{pgfonlayer}{backlayer2}
\fill[green] (0,0) circle (1.5);
\end{pgfonlayer}
\end{tikzpicture}
\end{document}
Note the order change even though the code is still ordered in the same way.

the code is still ordered in the same waybut on different ordered layers. – Ignasi Jun 21 '17 at 13:13