I would need to create a Sierpinski triangle in LaTeX, with numbers in the triangles.

As follows:

Sierpinski triangle

I have tried to modify the following code:

    \pgfdeclarelindenmayersystem{Sierpinski triangle}{
        \rule{X -> X-Y+X+Y-X}
        \rule{Y -> YY}

        l-system={step=\trianglewidth/(2^6), order=6, angle=-120}

    \fill [black] (0,0) -- ++(0:\trianglewidth) -- ++(120:\trianglewidth) -- cycle;
    \draw [draw=none] (0,0) l-system [l-system={Sierpinski triangle, axiom=X},fill=white];
\caption{Sierpiński Sieve.}

But without success :( How can I write numbers in the triangles??


You could use Mark Wibrow's solution, but it employs lualatex and if you don't already use it, it might not be worth it to switch to a different engine. Besides, that solution uses hexagons instead of triangles and it doesn't color them.

So here's an alternative version based on that answer but that has all the necessary changes. Plus it works with regular pdflatex, since we use pgfmath to do the proper calculations.


enter image description here



    regular polygon, regular polygon sides=3, 
    minimum size=2cm, inner sep=0pt,

\begin{tikzpicture}[x=2cm*sin 60, y=3cm*cos 60]

\foreach \n in {0,...,7}{
    \foreach \k in {0,...,\n}{ 
        \node[tris={draw,fill, text=white}] at (-\n/2+\k, -\n) {\fact};
        \node[tris] at (-\n/2+\k, -\n) {\fact};
  • Thank you very much!!. I could ask how to make the image smaller? Sep 5 '16 at 20:03
  • @DarioGutierrez No problem! You can add scale=0.8, every node/.style={transform shape} to the tikzpicture options (next to x=2cm*sin 60, y=3cm*cos 60).
    – Alenanno
    Sep 5 '16 at 20:07
  • @DarioGutierrez But scaling fonts in diagrams is not recommended.
    – cfr
    Sep 5 '16 at 22:17
  • @cfr wouldn't that scale text properly as well? If not, he can simply modify the x and y values, along with the node sizes.
    – Alenanno
    Sep 5 '16 at 22:43
  • That's my point. It is better not to scale text in diagrams to arbitrary sizes unless you really are stuck with no choice. It is better to use one of the standard sizes to ensure consistency.
    – cfr
    Sep 5 '16 at 23:59

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.