我正在尝试创建决策树并使边缘上的标签对齐。但是,如下图所示,两个边缘上的标签不在同一水平。我尝试使用pos=0.5
和midway
选项来解决这个问题,但显然这不起作用。有人能帮我吗?
\tikzset{
treenode/.style = {shape=rectangle, rounded corners,
draw, align=center,
%top color=white, bottom color=blue!20
},
dummy/.style = {circle,draw},
payoff/.style = {align=center}
}
\begin{tikzpicture}
[
%grow = right,
sibling distance = 10em,
level distance = 4em,
edge from parent/.style = {draw},
every node/.style = {font=\footnotesize},
%sloped
]
\node [treenode] {A}
child { node [payoff] {2\\2\\0}
edge from parent node [above,pos=0.5] {$b=0$} }
child { node [treenode] {B}
child { node [payoff] {0\\2\\0}
edge from parent node [above,pos=0.5] {R} }
child { node [payoff] {2b\\2b\\-5b}
edge from parent node [above,pos=0.5] {A}
}
edge from parent node [above] {$b \ne 0$}};
\end{tikzpicture}
答案1
编辑:目前,我看到了一些关于使用 TikZ 制作树的其他问题。似乎有一个功能更强大的软件包(但由于它基于 TikZ,可以将其制作成库,恕我直言)可以进行此类绘图:包裹forest
。事实上,有了它,语法会更简单一些,并且输出几乎总是占用更少的空间,请看一看:
\documentclass{standalone}
\usepackage{forest}
\forestset{
treenode/.style = {rounded corners, draw, base=top},
payoff/.style = {align=center, base=top}
}
\begin{document}
\begin{forest}
%for tree={l sep=1cm, s sep=1cm},
for tree={child anchor=north}
[A,treenode
[{2\\2\\0}, payoff, edge label={node[midway,left,font=\scriptsize]{$b=0$}}]
[B,treenode,edge label={node[midway,right,font=\scriptsize]{$b\neq 0$}}
[{0\\2\\0}, payoff, edge label={node[midway, left, font=\scriptsize]{R}}]
[{2b\\2b\\-5b}, payoff, edge label={node[midway, right, font=\scriptsize]{A}}]
]
]
\end{forest}
\end{document}
如你看到的,很多空间更小。虽然在这种情况下,树缩小太多看起来不太好,但不要害怕,因为可以控制空间。取消注释该行for tree={l sep=1cm, s sep=1cm},
以获得更好的结果,并更改s sep
值以扰乱父子距离和l sep
兄弟距离。
由于payoff
节点的大小并不完全相同,连接它们与父节点的线也不完全相同。如果使它们具有相同的宽度,那么一切都会好起来。为此,由于没有maximum width
选择,我们使用一个text width
(我还冒昧地为左侧和右侧edge
节点创建了一种样式,您可以根据需要进行更改):
\documentclass[border=5mm,tikz]{standalone}
\usetikzlibrary{trees}
\tikzset{
treenode/.style = {shape=rectangle, rounded corners,
draw, align=center,
%top color=white, bottom color=blue!20
},
payoff/.style = {align=center, inner sep=0.1em, text width=1.5em},
left side node/.style={above left, inner sep=0.1em},
right side node/.style={above right, inner sep=0.1em}
}
\begin{document}
\begin{tikzpicture}
[
%grow = right,
sibling distance = 10em,
level distance = 4em,
every node/.style = {font=\footnotesize},
%sloped
]
\node [treenode] {A} child{node[payoff] {2\\2\\0} edge from parent node[left side node] {$b=0$}}
child{node [treenode] {B}
child{ node [payoff] {0\\2\\0} edge from parent node[left side node] {R}}
child{ node [payoff] {2b\\2b\\-5b} edge from parent node[right side node] {A}}
edge from parent node[right side node] {$b\neq0$}
};
\end{tikzpicture}
\end{document}