以下代码生成如下所示的决策树:
我正在尝试为一些箭头添加标签,例如左下角箭头上的“x”。出于某种原因,我似乎无法在其他箭头上复制它?
\tikzset{
treenode/.style = {align=center, inner sep=0pt, text centered,
font=\sffamily}
}
\begin{figure}[h]
\centering
\begin{tikzpicture}[->,level/.style={sibling distance = 7cm/#1,
level distance = 2cm}]
\node [] {Bruises}
child{ node [] {Gill size}
child{ node [] {Spore Color}
child{ node [] {Yes} edge from parent node[above left] {$x$}} %for a named pointer
child{ node [] {No}}
}
child{ node [] {Habitat}
child{ node [] {Yes}}
child{ node [] {No}}
}
}
child{ node [] {Texture of stalk surface below ring}
child{ node [] {Number of rings}
child{ node [] {Yes}}
child{ node [] {No}}
}
child{ node [] {Odor}
child{ node [] {Yes}}
child{ node [] {No}}
}
}
;
\end{tikzpicture}
\caption{An example depth 3 decision tree built on the mush dataset.}
\end{figure}
答案1
为了避免在使用时产生混淆edge from parent node
,我认为最好的做法是给节点命名。这样,您就可以在任何节点之间以任意坐标绘制和添加路径。
这是一个例子。
\documentclass[tikz]{standalone}
\begin{document}
\tikzset{
treenode/.style = {align=center, inner sep=0pt, text centered,
font=\sffamily}
}
\begin{tikzpicture}[->,level/.style={sibling distance = 7cm/#1,
level distance = 2cm}]
\node [] {Bruises}
child{ node [] {Gill size}
child{ node [] {Spore Color}
child{ node [] {Yes} edge from parent node[above left] {abcd}} %for a named pointer
child{ node [] {No}}
}
child{ node [] (c) {Habitat}
child{ node [] {Yes}}
child{ node [] {No}}
}
}
child{ node [] {Texture of stalk surface below ring}
child{ node [] (a) {Number of rings}
child{ node [] (b) {Yes}}
child{ node [] {No}}
}
child{ node [] {Odor}
child{ node [] {Yes}}
child{ node [] {No}}
}
};
\path (a) -- (b) node[midway,above,sloped] {xyzt};
\draw[->,red] (a) -- (c) node[midway,above] {mn};
\end{tikzpicture}
\end{document}
答案2
我想forest
为此做广告cfr 的这个回答很不错。在我看来,语法变得更加简单,添加边标签就像添加一样简单,edge label=x
,当然,如果您愿意,可以添加更多箭头。
\documentclass{article}
\usepackage[edges]{forest}
\begin{document}
\begin{figure}[h]
\centering
\begin{forest}
/tikz/my edge label/.style={inner sep=5pt, midway},
for tree={edge={->},
l sep=4em,
s sep=3em,
anchor=center,
before typesetting nodes={
if n'=1{
edge label/.wrap value={\noexpand node [my edge label,right] {$#1$} }
}{
edge label/.wrap value={\noexpand node [my edge label,left] {$#1$} }
},
}
}
[Bruises
[Gill size
[Spore Color
[Yes,edge label=x]
[No,edge label=y]
]
[Habitat,alias=habitat
[Yes]
[No]
]
]
[Texture of stalk surface below ring,alias=texture
[Number of rings
[Yes]
[No]
]
[Odor
[Yes]
[No]
]
]
]
\draw[red,-latex,dashed] (texture) -- (habitat) node[midway,above,sloped]{$z$};
\end{forest}
\caption{An example depth 3 decision tree built on the mush dataset.}
\end{figure}
\end{document}