# tikz tree use pic as tree node

This question does not aim to explore something meaningful, but just for some interest.

Is there a way to use a pic as a "tree node" directly? It means that I can reference the named node or coordinate in pic after the tree has been draw.

Consider following pic just for example:

\documentclass[tikz, border=1cm]{standalone}
\makeatletter
\tikzset{
test n/.store in=\test@n,
test n=3,
test/.pic={
\foreach \x [evaluate=\x as \ang using (\x-1)*360/\test@n] in {1, ..., \test@n} {
\draw (0, 0) -- (\ang:5mm) coordinate (-\x);
}
}
}
\makeatother

\begin{document}
\begin{tikzpicture}
\pic (a) [test n=6] {test};
\draw[red] (a-1) -- (a-2);
\end{tikzpicture}
\end{document}


I'd like to use this pic in several nodes of the tree and reference the coordinates such as (a-1) after, is there a possible way to make it?

You can wrap a matrix around the pic.

\documentclass[tikz, border=1cm]{standalone}
\makeatletter
\tikzset{
test n/.store in=\test@n,
test n=3,
pics/test/.style={code={
\foreach \x [evaluate=\x as \ang using (\x-1)*360/\test@n] in {1, ..., \test@n} {
\draw (0, 0) -- (\ang:5mm) coordinate (-\x);
}
}}
}
\makeatother

\begin{document}
\begin{tikzpicture}
\node {root}
child {node[matrix] {\pic (a1) [test n=6] {test};\\}}
child {node[matrix] {\pic (a2) [test n=6] {test};\\}
child {node[matrix] {\pic (a3) [test n=6] {test};\\}}
child {node[matrix] {\pic (a4) [test n=8] {test};\\}}
};

\draw[red] (a1-1) -- (a1-2);
\draw[red] (a2-2) -- (a2-3);
\draw[red] (a3-4) -- (a3-5);
\end{tikzpicture}
\end{document}


This works also with forest.

\documentclass[varwidth, border=1cm]{standalone}
\usepackage{forest}
\makeatletter
\tikzset{
test n/.store in=\test@n,
test n=3,
pics/test/.style={code={
\tikzset{test/.cd,#1}%
\foreach \x [evaluate=\x as \ang using (\x-1)*360/\test@n] in {1, ..., \test@n} {
{\draw (0, 0) -- (\ang:5mm) coordinate (-\x);}
\pgfkeys{/tikz/test/extra}
}
}},test/.cd,extra/.code={}
}
\makeatother

\begin{document}
\begin{forest}
[pft
[{\pic (a1) [test n=6] {test};\\},matrix]
[{\pic (a2) [test n=6] {test};\\},matrix]
]
\end{forest}
\end{document}


The problem is to access the named pics from outside. forest does something to the pics, and accessing the named pics from outside is generally a bit tricky, so at this point I do not know how to solve that.

• Can this trick be used in forest package? – ZhiyuanLck Jun 9 '20 at 15:30
• @ZhiyuanLck I have not tried but would think so. – user194703 Jun 9 '20 at 15:32
• It seems that the content of [...] has been wrapped with node, I'm not familiar with forest package, but I know it is powerful. So I wonder how to do the same thing in this package. – ZhiyuanLck Jun 9 '20 at 15:36
• @ZhiyuanLck The basic trick works, accessing the nodes from outside is tricky. – user194703 Jun 9 '20 at 15:53
• It's ok, move to tex.stackexchange.com/questions/548612/… – ZhiyuanLck Jun 9 '20 at 16:08