我有一棵如下所示的简单树:
\documentclass[crop,tikz]{standalone}
\begin{document}
\begin{tikzpicture}[level/.style={level distance=20mm, sibling distance=20mm/#1}]
\node {(1)}
child {
node {(2)}
child {
node {...}
}
child {
node {...}
}
}
child {
node {(3)}
};
\end{tikzpicture}
\end{document}
现在我想在边缘添加一些标签,但树的形状看起来不正确。
\documentclass[crop,tikz]{standalone}
\begin{document}
\begin{tikzpicture}[level/.style={level distance=20mm, sibling distance=20mm/#1}]
\node {(1)}
child {
node {(2)} edge from parent node[pos=0.5, sloped, above,draw=none] {\emph{label1}}
child {
node {...} edge from parent node[pos=0.5, sloped, above,draw=none] {\emph{label2}}
}
child {
node {...} edge from parent node[pos=0.5, sloped, above,draw=none] {\emph{label3}}
}
}
child {
node {(3)} edge from parent node[right, pos=0.5, sloped, above,draw=none] {\emph{label4}}
};
\end{tikzpicture}
\end{document}
仅当为节点 (2) 指定来自父节点的边时才会发生错误。
无关问题 1:如何使用破折号来表示某些边缘,设置dashed
不起作用。
无关问题 2:如何使用多行标签作为节点。例如,我尝试使用 (3) 而不是 (4),$x=1$\\$y=2$
但不起作用。
答案1
Zarko 已经告诉了你图表扭曲的原因:你需要将边放在子节点后面。dashed
如果你将其用作边(而非节点)的选项,并且如果将其添加align=center
到节点选项,则可以将文本分为多行。
\documentclass[crop,tikz]{standalone}
\begin{document}
\begin{tikzpicture}[level/.style={level distance=20mm, sibling distance=20mm/#1}]
\node {(1)}
child {
node {(2)}
child {
node {...}
edge from parent node[pos=0.5, sloped, above,draw=none] {\emph{label2}}
}
child {node {...}
edge from parent[dashed] node[pos=0.5, sloped, above,draw=none] {\emph{label3}}
}
edge from parent node[pos=0.5, sloped,above,draw=none] {\emph{label1}}
}
child {
node[align=center] {$x=1$\\$y=2$}
edge from parent node[right, pos=0.5, sloped, above,draw=none] {\emph{label4}}
};
\end{tikzpicture}
\end{document}
答案2
每个问题一个问题...
您将边缘节点的代码放在了错误的位置,它应该位于分支的末尾:
\documentclass[crop,tikz]{standalone}
\begin{document}
\begin{tikzpicture}[
lbl/.style = {font=\itshape\footnotesize, sloped, above},
level/.style={level distance=20mm, sibling distance=20mm/#1}]
\node {(1)}
child {node {(2)}
child {node {...}
edge from parent node[lbl] {label-3}
}
child {node {...}
edge from parent node[lbl] {label-4}
}
edge from parent node[lbl] {label-1}
}
child {node {(3)}
edge from parent node[lbl] {label-2}
};
\end{tikzpicture}
\end{document}