I am trying to create a "classic" decision tree with forest. I have never used forest before and struggle with a couple of things. Unfortunately, I did not find the documentation an easy read. I found an answer that broad me a bit along the way (https://tex.stackexchange.com/a/251452/36836). I have adapted and changed it a bit. However, I would like to make the following further changes (partly) illustrated in the diagram below.
- Move the node labels (n_0, n_1, etc.) above the nodes (boxes/circles).
- Let the branches start at the east of the nodes (so that they don't interfere with the node labels.
- Make the nodes (boxes/circles) smaller (since they have no content anymore).
- Remove the triangles from the end and put the outcomes, o_1, o_2, etc, at directly after the edge (where the triangles were).
- Possibly, change the ordering so that the numbering starts from above rather than below, e.g. n_1 should be the node on top above n_2 and n_3.
- Move all settings into the preamble so that they are applied to all trees (maybe naming it "decision tree").
\documentclass{article}
\usepackage{etex,forest}
\usetikzlibrary{shapes,snakes}
\tikzset{
decision/.style={rectangle, minimum height=10pt, minimum width=10pt, draw=black, fill=white, thick, inner sep=0pt},
chance/.style={circle, minimum width=10pt, draw=black, fill=white, thick, inner sep=0pt},
leaf-chance/.style={isosceles triangle, minimum width=10pt, draw=black, thick, fill=white, inner sep=0pt, shape border rotate=180, outer sep=-\pgflinewidth}
}
\forestset{
declare toks={optimality}{},
sub optimal/.style={
optimality={
node [midway, sloped]
}
},
declare toks={edge label below}{},
}
\begin{document}
\begin{forest}
my label/.style={
edge label={node[midway,above,font=\scriptsize,text width=1.5cm,align=left]{#1}}
},
for tree={
grow=0,
font=\scriptsize,
child anchor=west,
anchor=west,
text ragged,
inner sep=1mm,
edge={thick},
l sep+=15mm,
s sep+=5mm,
if n children=0{
before typesetting nodes={
label/.wrap pgfmath arg={right:#1}{content()},
content={},
leaf-chance,
},
}{},
edge path={
\noexpand\path[\forestoption{edge}]
(!u.parent anchor) -- ([xshift=-15mm].child anchor)\forestove{optimality} -- (.child anchor)\forestoption{edge label below}\forestoption{edge label};
},
}
[$n_0$,decision
[$n_1$,decision,my label={$s_1$, $s_2$}
[$o_1$,chance,my label=$s_1(n_1)$]
[$o_2$,decision,my label=$s_2(n_1)$]
]
[$n_2$,decision,my label={$s_3$, $s_4$}
[$o_3$,decision,my label=$s_3(n_2)$]
[$o_4$,decision,my label=$s_4(n_2)$]
]
[$n_3$,decision,my label={$s_5$, $s_6$}
[$o_5$,decision,my label=$s_5(n_3)$]
[$o_6$,decision,my label=$s_6(n_3)$]
]
]
\end{forest}
\end{document}