我是 Tikz 的新手,我想创建一个类似于下图的决策树(我在 Paint 中创建)。有人知道我如何在 Latex 中做到这一点吗?
我的尝试离我想要的还很远:
\documentclass[tikz,border=5pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[grow=right]
\node(A){A}
child[sibling distance=25mm]{node{1}
child{node{} edge from parent[] node[right,xshift=10]{}
child[sibling distance=10mm]{node{5}
child{node{} edge from parent[] node[right,xshift=10]{}}
}
child[sibling distance=10mm]{node{6}
child{node{} edge from parent[] node[right,xshift=10]{}}
}
}
}
child[sibling distance=25mm]{node{2}
child{node{} edge from parent[] node[right,xshift=10]{}
child[sibling distance=10mm]{node{3}
child{node{} edge from parent[] node[right,xshift=10]{}}
}
child[sibling distance=10mm]{node{4}
child{node{} edge from parent[] node[right,xshift=10]{}}
}
}
};
\node[left=of A](B){B};
\draw[](B)--(A);
\end{tikzpicture}
\end{document}
答案1
一份快速的森林提案。
\documentclass[border=3.14mm]{standalone}
\usepackage{forest}
\begin{document}
\begin{forest}
for tree={grow'=east,child anchor=south east,parent anchor=south east,edge=thick}
[[Label1[
[[Label2
[[Label 4
[[Label 6
[[Label 10]]
]]
[[Label 7
[[Label 11]]
]]
]]
]]
[[Label3
[[Label 5
[[Label 8
[[Label 11]]
]]
[[Label 9
[[Label 12]]
]]
]]
]]
]]]
\end{forest}
\end{document}
答案2
不太快速的森林提案。由于您的 MWE(确定树中的节点)和草图(不清楚它是否仅确定边缘标签或节点)在树的级别数量上有所不同,因此我不清楚这个问题。两者之间的折衷是:
\documentclass[margin=3mm]{standalone}
\usepackage{forest}
\begin{document}
\forestset{
anchors/.style={anchor=#1,child anchor=#1,parent anchor=#1},
decision edge label/.style n args=2{%
edge label/.expanded={node[pos=0.48, inner sep=1pt, anchor=#1]{#2}}
},
decision/.style={if n=1{decision edge label={south}{#1}}
{decision edge label={north}{#1}}
},
decision tree/.style={
for tree={
/tikz/every node/.append style={font=\footnotesize},
font=\normalsize, inner xsep=4pt,
grow' = east,
if n children=1{anchors=east}{anchors=west},
if level = 1{l sep=24mm,s sep=4mm}{l sep=8mm,s sep=3mm},
edge path'={
(!u.parent anchor) -- ([xshift=2mm]!u.parent anchor |- .child anchor) -- (.child anchor)
},
},
delay={for descendants={split option={content}{;}{content,decision}}},
}% end of decision tree
}% end of forestset
%---------------------------------------------------------------%
\begin{forest} decision tree
[
[1; in
[1;option 11\quad text
[;aaa]
[;bbb]
]
[2;option 12\quad text
[;ccc]
[;ddd]
]
]
]
\end{forest}
\end{document}