我想使用 Tikz 为我正在写的演讲生成树的图片。我需要能够为树的边缘着色并为每个边缘添加数字权重。我有可以完成第一项任务的代码,我想知道是否有一种简单的方法可以让它完成第二项任务。(我在其他地方见过带有加权边缘的 Tikz 树的示例,在这些示例中,顶点似乎需要绘制到树中,而我不希望我的树中有顶点。)
$\begin{tikzpicture}[thick, level distance=6mm]
\tikzstyle{level 2}=[sibling distance=15mm]
\tikzstyle{level 3}=[sibling distance=5mm]
\coordinate
child[blue]
{
child[blue] {child child}
child[blue] {child child[blue]}
child[red] {child {child} child child[red]}
} ;
\end{tikzpicture}$
这样就得到了下图,这大致就是我想要的。但是我该如何给每条边添加权重呢?
答案1
像这样?
\documentclass[tikz, margin=3mm]{standalone}
\begin{document}
\begin{tikzpicture}[
thick,
level distance = 6mm,
level 2/.style = {sibling distance=15mm},
level 3/.style = {sibling distance=5mm},
every node/.append style = {font=\footnotesize}
]
\coordinate
child[blue]
{
child[blue] {child {
edge from parent node[left] {1}
}
child {
edge from parent node[right] {2}
}
edge from parent node[left] {a}
}
child[red] {child {child {
edge from parent node[left] {5}
}
edge from parent node[left] {3}
}
child {
edge from parent node[right] {4}
}
edge from parent node[right] {b}
}
edge from parent node[right] {ab}
} ;
\end{tikzpicture}
\end{document}
答案2
edge from parent
自动插入获取。您可以使用键对其进行修改。edge from parent path
这里有一个修改,允许您使用quotes
语法在其上放置边缘标签。然后您只需要在边缘上说child[el={"2"}]
获取,如果您说,则将被交换,即在另一侧。2
child[el={"2"'}]
2
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{quotes}
\begin{document}
\begin{tikzpicture}[thick, level distance=6mm,
level 2/.style={sibling distance=15mm},
level 3/.style={sibling distance=5mm,pos=0.8},
edge from parent path={
(\tikzparentnode\tikzparentanchor) edge[my el]
(\tikzchildnode\tikzchildanchor)},
el/.code={\tikzset{my el/.style={#1}}},
my el/.style={},
font=\footnotesize]
\coordinate
child[blue]
{
child[blue,el={"1"'}] {
child[el={"2"'}]
child[el={"3"}]
}
child[blue,el={"4"'}] {
child[el={"5"'}]
child[blue,el={"6"}]}
child[red,el={"7"}] {
child[el={"8"'}] {
child[el={"9"'}]}
child[el={"5"}]
child[red,el={"11"}]}
} ;
\end{tikzpicture}
\end{document}