TransWikia.com

Tikz: Setting an anchor in a pic for relative positioning

TeX - LaTeX Asked by PatrickT on April 23, 2021

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

One Answer

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=letmylntikzlastnode]
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

Correct answer by user240002 on April 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP