![使用幻影节点调整节点级别](https://linux22.com/image/476922/%E4%BD%BF%E7%94%A8%E5%B9%BB%E5%BD%B1%E8%8A%82%E7%82%B9%E8%B0%83%E6%95%B4%E8%8A%82%E7%82%B9%E7%BA%A7%E5%88%AB.png)
考虑MWE:
\documentclass[landscape]{article}
\usepackage{tikz}
\usetikzlibrary{shapes,arrows}
\begin{document}
\tikzset{
treenode/.style = {align=center, inner sep=2pt, rounded corners = 2pt, minimum width = 2cm, text centered, font=\sffamily},
block/.style = {treenode, rectangle, white, font=\sffamily\bfseries, draw=black, fill=black},
phantom/.style = {}
}
\begin{tikzpicture}[->,>=stealth',level/.style={sibling distance = 3in/#1, level distance = 1.5cm}]
\node [block] {P1}
child {node [block] {P2}
child {node [block] {P3}
child {node [block] {P4}}
child {node [block] {P5}}
}
}
child {node [block] {P6}
child {node [phantom] {}
child {node [block] {P7}}
}
}
child {node [block] {P8}
child {node [block] {P9}
child {node [block] {P10}}
}
}
;
\end{tikzpicture}
\end{document}
我正在使用幻影节点让 P7 与 P4、P5 和 P10 处于同一级别。
但是在幻影节点的位置,我得到了一些空白空间,来自 P6 的连接器终止于此,并且新的连接器从该空白空间开始到 P7。
如何获得从 P6 到 P7 的直连接器?通常,我们如何调整各个节点的“级别”?
答案1
在这种情况下,forest
可能会有所帮助;tier
关键是让您毫不费力地获得所需的对齐(还请注意较短的代码):
\documentclass{article}
\usepackage{forest}
\tikzset{
treenode/.style={
align=center,
inner sep=2pt,
rounded corners=2pt,
minimum width = 2cm,
font=\sffamily
},
block/.style={
treenode,
rectangle,
white,
font=\sffamily\bfseries,
draw=black,
fill=black
},
phantom/.style = {}
}
\begin{document}
\begin{forest}
for tree={
block,
edge={->,>=latex},
where level={0}{s sep=1.5cm}{}
}
[P1
[P2
[P3
[P4]
[P5,tier=last]
]
]
[P6,before computing xy={s=(s("!p")+s("!n"))}
[P7,tier=last]
]
[P8
[P9]
[P10,tier=last]
]
]
\end{forest}
\end{document}
由于节点的当前标签方案也可以留给包,因此代码可以更短。
答案2
这是一个可行的解决方案。要删除空格,请使用coordinate
而不是node
,这里
edge from parent/.style={draw=none}
用于不绘制从 P6 到 P7 的线,然后手动绘制 (P6)--(P7) 线。
代码
\documentclass[border=1cm]{standalone}
%\documentclass[landscape]{article}
\usepackage{tikz}
\usetikzlibrary{shapes,arrows}
\begin{document}
\tikzset{
treenode/.style = {align=center, inner sep=2pt, rounded corners = 2pt, minimum width = 2cm, text centered, font=\sffamily},
block/.style = {treenode, rectangle, white, font=\sffamily\bfseries, draw=black, fill=black},
phantom/.style = {},
}
\begin{tikzpicture}[->,>=stealth',
level/.style={sibling distance = 3in/#1, level distance = 1.5cm}
]
\node [block] {P1}
child {node [block] {P2}
child {node [block] {P3}
child {node [block] {P4}}
child {node [block] {P5}}
}
}
child {node [block](a) {P6}
child {coordinate [phantom,edge from parent/.style={draw=none}] {}
child {node [block](b) {P7}}
}
}
child {node [block] {P8}
child {node [block] {P9}
child {node [block] {P10}}
}
}
;
\draw[->] (a)--(b);
\end{tikzpicture}