# creating a background for a group of nodes

How can I put a background for a group of nodes (but the group of nodes is created before drawing the background). The problem is that if I draw a rectangle before creating the group (i.e. before calling the macro \graphcircuit) it will be on top of the graph, and on the other side I can't draw the background without having the group (size I dont know the size of the group).

The code below is from the answer Positioning a node with respect to a group of nodes which was derived from the answer tikz: How to pass a list as a parameter of a tikz macro and use it in a foreach inside the macro

\documentclass[tikz]{standalone}
\usetikzlibrary{fit}

\newcommand{\graphcircuit}[1]{
\begin{scope}
\def\myfitarray{}
\foreach[count=\n] \v in {#1}; % count the number of elements
\pgfmathsetmacro{\r}{\n*0.2} % set the node distance from (0,0)
\pgfmathsetmacro{\b}{90/\n} % evaluate the bend angle
\foreach[count=\i, evaluate=\i as \a using (\i-1)*360/\n] \v in {#1}
\node [circle, draw, font=\scriptsize] (n-\i) at (\a:\r) {$\v$};
\foreach \i [remember=\i as \j (initially \n)] in {1,...,\n}{
\draw[semithick,-stealth] (n-\j) to[bend right=\b] (n-\i);}
\foreach \x in {1,...,\n}{%
\expandafter\xdef\expandafter\myfitarray\expandafter{\myfitarray (n-\x)}}
\node[inner sep=2pt,fit=\myfitarray] (groupnode) {};
\end{scope}
}

\begin{document}
\begin{tikzpicture}
\graphcircuit{1:5,7:2,3:0,4:0,9:1}
\node[font=\normalsize,anchor=south] (A) at (groupnode.north) {(A)};
\fill[cyan!15] (groupnode.south west) rectangle (groupnode.north east);
\end{tikzpicture}
\end{document}


You can use the backgrounds library to fill the node behind the group after drawing it:

\documentclass[tikz]{standalone}
\usetikzlibrary{fit,backgrounds}

\newcommand{\graphcircuit}[1]{
\begin{scope}
\def\myfitarray{}
\foreach[count=\n] \v in {#1}; % count the number of elements
\pgfmathsetmacro{\r}{\n*0.2} % set the node distance from (0,0)
\pgfmathsetmacro{\b}{90/\n} % evaluate the bend angle
\foreach[count=\i, evaluate=\i as \a using (\i-1)*360/\n] \v in {#1}
\node [circle, draw, font=\scriptsize] (n-\i) at (\a:\r) {$\v$};
\foreach \i [remember=\i as \j (initially \n)] in {1,...,\n}{
\draw[semithick,-stealth] (n-\j) to[bend right=\b] (n-\i);}
\foreach \x in {1,...,\n}{%
\expandafter\xdef\expandafter\myfitarray\expandafter{\myfitarray (n-\x)}}
\node[inner sep=2pt,fit=\myfitarray] (groupnode) {};
\end{scope}
}

\begin{document}
\begin{tikzpicture}
\graphcircuit{1:5,7:2,3:0,4:0,9:1}
\node[font=\normalsize,anchor=south] (A) at (groupnode.north) {(A)};
\scoped[on background layer]{
\fill[cyan!15] (groupnode.south west) rectangle (groupnode.north east);}
\end{tikzpicture}
\end{document}