我正在用 LaTeX 写一篇论文,并尝试使用 TikZ 插入一个简单的决策树图。但是,我不擅长使用 TikZ,而且我的树有两个小问题。
这是我现在的树,我在两个方面遇到了麻烦:
- 我想去掉顶部 R=0 之前的多余水平线。
- 我希望节点位于圆圈内。
再说一遍,我不擅长使用 TikZ,似乎无法让它工作。我的代码如下。
{
% Set the overall layout of the tree
\tikzstyle{level 1}=[level distance=3.5cm, sibling distance=3.5cm]
\tikzstyle{level 2}=[level distance=3.5cm, sibling distance=2cm]
% Define styles for bags and leafs
\tikzstyle{bag} = [text width=4em, text centered]
\tikzstyle{end} = [circle, minimum width=3pt,fill, inner sep=0pt]
%TODO: fix top node
\begin{figure}[h]
\centering
\begin{tikzpicture}[grow=right, sloped, scale=0.8]
\node[bag] {$L$}
child {
node[bag] {$D$}
child {
node[bag] {$P$}
child {
node[bag] {$C$}
child {
node[end, label=right:
{$\mathbf{R=1}$}] {}
edge from parent
%node[above] {$E$}
node[below] {$C=0$}
}
child {
node[end, label=right:
{$\mathbf{R=0}$}] {}
edge from parent
%node[above] {$E$}
node[below] {$C=1$}
}
edge from parent
%node[above] {$E$}
node[below] {$P=0$}
}
child {
node[end, label=right:
{$\mathbf{R=0}$}] {}
edge from parent
%node[above] {$E$}
node[below] {$P=1$}
}
edge from parent
%node[above] {$W$}
node[below] {$D=0$}
}
child {
node[end, label=right:
{$\mathbf{R=0}$}] {}
edge from parent
%node[above] {$E$}
node[below] {$D=1$}
}
edge from parent
%node[above] {$W$}
node[below] {$L=0$}
}
child {
child {
node[end, label=right:
{$\mathbf{R=0}$}] {}
edge from parent
%node[above] {$E$}
%node[below] {$C=0$}
}
edge from parent
%node[above] {$B$}
node[below] {$L=1$}
};
\end{tikzpicture}
\end{figure}
}
如果有比我更擅长 TikZ 的人可以帮助我解决这个问题,我将不胜感激。
答案1
我在以下人员的帮助下找到了答案https://tex.stackexchange.com/a/240766/77231。
这是我的新照片:
我的新代码:
\documentclass[tikz]{standalone}
\usepackage{forest}
\begin{document}
\tikzset{
decision/.style={circle, minimum height=10pt, minimum width=10pt, draw=black, fill=none, thick, inner sep=0pt},
chance/.style={circle, minimum width=10pt, draw=black, fill=none, thick, inner sep=0pt},
}
\begin{forest}
my label/.style={
edge label={node[auto,sloped,pos=.75,anchor=south]{#1}}
},
for tree={
grow=0,
child anchor=west,
anchor=west,
text ragged,
inner sep=1mm,
edge={thick, draw=black},
l sep+=15mm,
s sep+=15mm,
if n children=0{
before typesetting nodes={
label/.wrap pgfmath arg={right:#1}{content()},
content={},
chance,
},
}{},
edge path={
\noexpand\path [draw, \forestoption{edge}] (!u.parent anchor) |- (.child anchor)\forestoption{edge label};
}
}
[, decision
[, chance, my label={$L=0$}
[, chance, my label={$D=0$}
[, chance, my label={$P=0$}
[{$\mathbf{R=1}$}, my label={$C=0$}
]
[{$\mathbf{R=0}$}, my label={$C=1$}
]
]
[{$\mathbf{R=0}$}, my label={$P=1$}
]
]
[{$\mathbf{R=0}$}, my label={$D=1$}
]
]
[{$\mathbf{R=0}$}, my label={$L=1$}
]
]
\end{forest}
\end{document}
我认为这更简洁、更好。再次感谢 cfr 的回答https://tex.stackexchange.com/a/240766/77231!