10

I am trying to make a L-system in TikZ using the lindenmayersystems library:

I have this code:

\documentclass[border=1cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{lindenmayersystems}
\pgfdeclarelindenmayersystem{A}{
\rule{A->F[+A][-A]}
}
\begin{document}
\begin{tikzpicture}[scale=10,rotate=90]
\draw
    [blue,opacity=0.5,line width=0.5cm,line cap=round]
    l-system [l-system={A,axiom=A
    ,order=4,angle=45,step=0.25cm}];
\end{tikzpicture}
\end{document}

This code is producing this output:

But as you can see, the top branches of the tree are touching each other. I do not want this to happen. I want that the size of the line should be reduced with every step, like in the following wikipedia image:

Is there any way to do this in TikZ?

10

One solution is to define the symbol F in a way which reduces the value of \pgflsystemstep, i.e:

\pgfdeclarelindenmayersystem{A}{
  \symbol{F}{\pgflsystemstep=0.6\pgflsystemstep\pgflsystemdrawforward}
  \rule{A->F[+A][-A]}
}

Which gives:

Result

Complete code for the above figure:

\documentclass{article}
\usepackage{tikz}
\usepackage[active,tightpage]{preview}\PreviewEnvironment{tikzpicture}
\usetikzlibrary{lindenmayersystems}
\pgfdeclarelindenmayersystem{A}{
\symbol{F}{\pgflsystemstep=0.6\pgflsystemstep\pgflsystemdrawforward}
\rule{A->F[+A][-A]}
}
\begin{document}
\foreach \n in {1,...,8} {
\begin{tikzpicture}[scale=10,rotate=90]
\draw (-.1,-.2) rectangle (.4,0.2);
\draw
    [blue,opacity=0.5,line width=0.1cm,line cap=round]
    l-system [l-system={A,axiom=A
    ,order=\n,angle=45,step=0.25cm}];
\end{tikzpicture}
}

\end{document}

Update

A better solution: Define a new symbol (eg, S for "scale") which changes the scale, but draws nothing. The advantage is that it can be used in any part of the rule.

Using this approach, your example would be:

\pgfdeclarelindenmayersystem{A}{
  \symbol{S}{\pgflsystemstep=0.6\pgflsystemstep}
  \rule{A->SF[+A][-A]}
}

Another example, which shows how the "scaling" can be used in a part of a rule, could be:

\pgfdeclarelindenmayersystem{A}{
  \symbol{S}{\pgflsystemstep=0.5\pgflsystemstep}
  \rule{A->F[+A][-A]SA}
}

which, used this way:

\foreach \n in {1,...,6} {
\begin{tikzpicture}[scale=10,rotate=90]
\draw (-.03,-.17) rectangle (.35,0.17);
\draw
    [blue,opacity=0.5,thin,line cap=round]
    l-system [l-system={A,axiom=A
    ,order=\n,angle=15,step=0.05cm}];
\end{tikzpicture}
}

produces

Second example

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.