我有一棵简单的树。我不知道如何垂直对齐子项。
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node {0}
child {node {a}}
child {node {b}}
child {node {c}
child {node {a1}}
child {node {b1}}
child {node {c1}}
child {node {d1}}
}
child {node {d}}
;
\end{tikzpicture}
\end{document}
编译代码会在节点 c 下产生一个子树,但我希望 x 和 x1 垂直对齐。我必须手动放置每个节点吗?像below of=a
miss 这样的选项会对齐剩余的子节点。我正在寻找像leftalign
整棵树这样的东西。
答案1
我不确定这是否是您想要的,但您可以将某一级别的节点向左和向右移动(因为默认的同级距离是 15 毫米,为了垂直对齐节点,您需要将所有节点移动该值的一半,即 7.5 毫米):
\documentclass[border=10pt]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[level 2/.style={every node/.style={xshift=-7.5mm}}]
\node {0}
child {node {a}}
child {node {b}}
child {node {c}
child {node {a1}}
child {node {b1}}
child {node {c1}}
child {node {d1}}
}
child {node {d}}
;
\end{tikzpicture}
\end{document}
如果缺少一个节点,则上述情况会有所变化:
\documentclass[border=10pt]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[level 2/.style={sibling distance=22.5mm, every node/.style={xshift=-7.5mm}}]
\node {0}
child {node {a}}
child {node {b}}
child {node {c}
child {node {a1}}
child {node {b1}}
child {node {d1}}
}
child {node {d}}
;
\end{tikzpicture}
\end{document}
\documentclass[border=10pt]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[level 2/.style={every node/.style={xshift=-7.5mm}}]
\node {0}
child {node {a}}
child {node {b}}
child {node {c}
child {node {a1}}
child {node {b1}}
child[missing] {}
child {node {d1}}
}
child {node {d}}
;
\end{tikzpicture}
\end{document}
也许,你也可以尝试这个forest
包:
\documentclass[border=10pt]{standalone}
\usepackage{forest}
\begin{document}
\begin{forest} for tree={node options={text width=1.25em, align=center}}
[0
[a]
[b]
[c
[a1]
[b1]
[c1, calign with current]
[d1]
]
[d]
]
\end{forest}
\end{document}
\documentclass[border=10pt]{standalone}
\usepackage{forest}
\begin{document}
\begin{forest} for tree={node options={text width=1.25em, align=center}}
[0
[a]
[b]
[c
[a1]
[b1]
[, phantom, calign with current]
[d1]
]
[d]
]
\end{forest}
\end{document}