# Layer generation in TikZ [duplicate]

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 question is interesting but could you add a MWE? – CarLaTeX Jun 21 '17 at 12:59
• You can copy the code from the library to create as many layers as you wish and then use them in the same way as the pre-defined one. However, you have to define all the layers you need and set the hierarchy so that TikZ knows what to draw first. – cfr Jun 21 '17 at 13:04
• the code is still ordered in the same way but on different ordered layers. – Ignasi Jun 21 '17 at 13:13
• @Symbol1 Very nice, I did not find it myself. I will close this question. – Huang_d Jun 21 '17 at 16:19