我已经使用 绘制了一棵树tikz-qtree
,并想为其(直接)子节点上方的每个节点绘制一个背景矩形。现在我\node
在绘制树时使用,然后手动逐个添加背景矩形;请参阅下面的代码和图。有什么方便的方法吗(想象一下它是一棵巨大的树。)?
使用其他软件包的答案也tikz-qtree
同样值得赞赏。
\documentclass{standalone}
\usepackage{tikz}
\usepackage{tikz-qtree}
\usetikzlibrary{backgrounds, fit}
\begin{document}
\begin{tikzpicture}
\Tree [.\node (1234567) {$n_1n_2n_3n_4n_5n_6n_7$};
[.\node (123) {$n_1n_2n_3$};
[.\node (1) {$n_1$}; ]
[.\node (23) {$n_2n_3$};
[.\node (2) {$n_2$}; ]
[.\node (3) {$n_3$}; ]]]
[.\node (4567) {$n_4n_5n_6n_7$};
[.\node (45) {$n_4n_5$};
[.\node (4) {$n_4$}; ]
[.\node (5) {$n_5$}; ]]
[.\node (67) {$n_6n_7$};
[.\node (6) {$n_6$}; ]
[.\node (7) {$n_7$}; ]]]]
\begin{pgfonlayer}{background}
% manually add background rectangles one by one
\node () [rectangle, draw, fit = (2) (3), inner sep = 0pt] {};
\node () [rectangle, draw, fit = (4) (5), inner sep = 0pt] {};
\node () [rectangle, draw, fit = (6) (7), inner sep = 0pt] {};
\node () [rectangle, draw, fit = (1) (23), inner sep = 0pt] {};
\node () [rectangle, draw, fit = (45) (67), inner sep = 0pt] {};
\node () [rectangle, draw, fit = (123) (4567), inner sep = 0pt] {};
\end{pgfonlayer}
\end{tikzpicture}
\end{document}
答案1
这里有一个更简单的方法,使用forest
。我创建了一个节点样式,它适合当前节点子节点周围的矩形。然后使用条件\if nodewalk valid
,我将样式应用于具有子节点的节点。
\documentclass[border=10pt]{standalone}
\usepackage[linguistics]{forest}
\forestset{child frame/.style=
{tikz={\node () [rectangle, red,draw, fit to=children,inner sep = 0pt] {};}}}
\begin{document}
\begin{forest}for tree={if nodewalk valid={l}{child frame}{}}
[$n_1n_2n_3n_4n_5n_6n_7$
[$n_1n_2n_3$
[$n_1$ ]
[$n_2n_3$
[$n_2$ ]
[$n_3$ ]]]
[$n_4n_5n_6n_7$
[$n_4n_5$
[$n_4$ ]
[$n_5$ ]]
[$n_6n_7$
[$n_6$ ]
[$n_7$ ]]]]
\end{forest}
\end{document}