@@ -117,11 +117,27 @@ def hierarchy_pos(
117117 if not nx .is_tree (G ):
118118 raise TypeError ("cannot use hierarchy_pos on a graph that is not a tree" )
119119
120+ # These get swapped if tree edge directions point to the root.
121+ decendants = nx .descendants
122+ out_degree = G .out_degree
123+ neighbors = G .neighbors
124+
120125 if root is None :
121126 if isinstance (G , nx .DiGraph ):
122- root = next (
123- iter (nx .topological_sort (G ))
124- ) # allows back compatibility with nx version 1.11
127+ zero_outs = [n for n in G .out_degree () if n [1 ] == 0 ]
128+ if len (zero_outs ) == 1 and len (G ) > 2 :
129+ # We unequivocally have a directed that points from leave to the root.
130+ # The case where we have a one or two node graph is ambiguous.
131+ root = list (nx .topological_sort (G ))[- 1 ]
132+ # Swap motion functions
133+ decendants = nx .ancestors
134+ out_degree = G .in_degree
135+ neighbors = G .predecessors
136+ else :
137+ root = next (
138+ iter (nx .topological_sort (G ))
139+ ) # allows back compatibility with nx version 1.11
140+ # root = next(nx.topological_sort(G))
125141 else :
126142 root = random .choice (list (G .nodes ))
127143
@@ -152,7 +168,8 @@ def _hierarchy_pos(
152168 rootpos [root ] = (xcenter , vert_loc )
153169 if leafpos is None :
154170 leafpos = {}
155- children = list (G .neighbors (root ))
171+
172+ children = list (neighbors (root ))
156173 leaf_count = 0
157174 if not isinstance (G , nx .DiGraph ) and parent is not None :
158175 children .remove (parent )
@@ -188,9 +205,7 @@ def _hierarchy_pos(
188205
189206 xcenter = width / 2.0
190207 if isinstance (G , nx .DiGraph ):
191- leafcount = len (
192- [node for node in nx .descendants (G , root ) if G .out_degree (node ) == 0 ]
193- )
208+ leafcount = len ([node for node in decendants (G , root ) if out_degree (node ) == 0 ])
194209 elif isinstance (G , nx .Graph ):
195210 leafcount = len (
196211 [
@@ -199,6 +214,7 @@ def _hierarchy_pos(
199214 if G .degree (node ) == 1 and node != root
200215 ]
201216 )
217+
202218 rootpos , leafpos , leaf_count = _hierarchy_pos (
203219 G ,
204220 root ,
0 commit comments