3

I have created a pic of a simple polygon which I want to use and reuse to create tikzpictures containing copies of it positioned relative to each other. How do I do that?

If I did not have the pic, I would use the positioning library and position relative to the polygon's corners. Can I do something similar here with a pic?

The expected result is something more elegant and reproducible than this. Thanks.

\documentclass[class=article,border=5pt,tikz]{standalone}
\usetikzlibrary{shapes.geometric}

\tikzset{fig/.pic={code={%
  \begin{scope}
   \node[regular polygon,regular polygon sides=6,draw,minimum width=3cm]
   (hexagon){};
   \foreach \x [evaluate=\x] in {1,...,6}
   {\node[draw,shape=circle,fill=white,opacity=1,minimum size=6mm] at (hexagon.corner \x){}; }
  \end{scope}
}}}%

\begin{document}
\begin{tikzpicture}[thick,x=1cm,y=1cm]
  \path (0,0) pic {fig};
  \path (2.265,1.305) pic {fig}; # inelegant + imprecise!
  \path (4.53,0) pic {fig};
  \path (2.265,-1.305) pic {fig};
\end{tikzpicture}
\end{document}

enter image description here

6

In this case, I would not use a pic but append after command. One benefit is that you can use the anchors of the node.

\documentclass[class=article,border=5pt,tikz]{standalone}
\usetikzlibrary{shapes.geometric}

\tikzset{myhex/.style={regular polygon,regular polygon sides=6,draw,
    outer sep=0pt,minimum width=3cm,
    append after command={[/utils/exec=\let\myln\tikzlastnode]
foreach \x  in {1,...,6} {(\myln.corner \x)
node[draw,shape=circle,fill=white,opacity=1,minimum size=6mm]{}}
}}}%

\begin{document}
\begin{tikzpicture}[thick,x=1cm,y=1cm]
  \path (0,0) node[myhex] (h1) {}
    node[myhex,anchor=corner 3]  (h2) at (h1.corner 1){}
    node[myhex,anchor=corner 3]  (h3) at (h1.corner 5){}
    node[myhex,anchor=corner 3]  (h4) at (h2.corner 5){};
\end{tikzpicture}
\end{document}

enter image description here

1
  • 1
    Oh that's great. I didn't know the append after command style. Thanks! – PatrickT Apr 19 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.