我使用类似于以下代码绘制了一个目录列表样式树 使用 TikZ 中的 tree 命令绘制目录列表。为了清楚起见,我在这里重复一下
\documentclass[border=10]{standalone}
\usepackage{tikz}
\makeatletter
\newcount\dirtree@lvl
\newcount\dirtree@plvl
\newcount\dirtree@clvl
\def\dirtree@growth{%
\ifnum\tikznumberofcurrentchild=1\relax
\global\advance\dirtree@plvl by 1
\expandafter\xdef\csname dirtree@p@\the\dirtree@plvl\endcsname{\the\dirtree@lvl}
\fi
\global\advance\dirtree@lvl by 1\relax
\dirtree@clvl=\dirtree@lvl
\advance\dirtree@clvl by -\csname dirtree@p@\the\dirtree@plvl\endcsname
\pgf@xa=1cm\relax
\pgf@ya=-1cm\relax
\pgf@ya=\dirtree@clvl\pgf@ya
\pgftransformshift{\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
\ifnum\tikznumberofcurrentchild=\tikznumberofchildren
\global\advance\dirtree@plvl by -1
\fi
}
\tikzset{
dirtree/.style={
growth function=\dirtree@growth,
every node/.style={anchor=north},
every child node/.style={anchor=west},
edge from parent path={(\tikzparentnode\tikzparentanchor) |- (\tikzchildnode\tikzchildanchor)}
}
}
\makeatother
\begin{document}
\begin{tikzpicture}[dirtree]
\node {toplevel}
child { node {Foo}
child { node {foo} }
child { node {bar} }
child { node {baz} }
}
child { node {Bar}
child { node {foo} }
child { node {foo} }
child { node {foo} }
child { node {foo} }
child { node {bar} }
child { node {baz} }
}
child { node {Baz}
child { node {foo} }
child { node {bar} }
child { node {baz} }
};
\end{tikzpicture}
\end{document}
我的问题是:如何减少子节点的缩进?
目前,锚点位于父节点的南边,这意味着树在水平方向上会很快变大。我不希望使用父节点的西边作为锚点。理想情况下,两者之间的一个点会更好,因此输出如下所示:
Root
|___ First Parent
|__First Child
|_ Grand Child
而不是
Root
|___ First Parent
|__First Child
|_ Grand Child
任何想法都非常感谢
答案1
让我们提供一个不同的例子来更好地展示你的问题:
% Assumming preamble as provided in the question
\tikzset{
dirtree/.style={
growth function=\dirtree@growth,
every node/.style={anchor=north},
every child node/.style={anchor=west},
edge from parent path={(\tikzparentnode\tikzparentanchor) |- (\tikzchildnode\tikzchildanchor)}
}
}
\makeatother
\begin{document}
\begin{tikzpicture}[dirtree]
\node {toplevel}
child { node {Foobarish}
child { node {foobar}
child { node {foo}}
}
child { node {foo}
child {node {foo} }
}
child { node {bar} }
}
child { node {Bar}
child { node {foo} }
child { node {foo} }
};
\end{tikzpicture}
输出为:
这不仅表明了您提到的问题,还表明每个分支中的垂直茎未对齐(来自的分支Foobarish
与来自的分支未对齐Bar
)。这个问题也可以通过适当的parent anchor
(和growth parent anchor
)来解决,它不依赖于父级的大小。在这种情况下south west
是最佳选择。
以下样式解决了所有这些问题,并提供了非常紧凑的树版本。
\tikzset{
dirtree/.style={
growth function=\dirtree@growth,
growth parent anchor=south west,
parent anchor=south west,
every child node/.style={anchor=west},
edge from parent path={([xshift=2ex] \tikzparentnode\tikzparentanchor)
|- (\tikzchildnode\tikzchildanchor)}
}
}
感谢 Andrew Stacey 和 Jake 对需要设置的有用评论growth parent anchor
(他们下面的评论指的是这个答案的早期版本)。