使用虛擬節點調整節點級別

使用虛擬節點調整節點級別

考慮 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}

相關內容