NetworkX - Stop Nodes from Bunching Up - Tried Scale/K parameters

后端 未结 1 478
甜味超标
甜味超标 2021-01-16 04:21

I have ~28 nodes with edges between most of them, and some being isolated (no edges). The isolated nodes are spread out nicely, but the ones which are connected are so stac

1条回答
  •  离开以前
    2021-01-16 04:50

    There are several ways to do this.

    First a comment on how networkx draws things. Here's the documentation. It creates a dictionary pos which has the coordinates of each node. Using draw_networkx you can send the optional argument pos=my_position_dict to it.

    Networkx also has commands that will define the positons for you. This way you can have more control over things.

    You have several options to do what you want.

    The simplest is to plot just the connected component and leave out the isolated nodes.

    nodes_of_largest_component  = max(nx.connected_components(G), key = len)
    largest_component = G.subgraph(nodes_of_largest_component)
    nx.draw_spring(largest_component)
    

    Another would be to try one of the other (non-spring) layouts. For example:

    nx.draw_spectral(G)
    

    Alternately, you can start manipulating the positions. One way is to set a couple positions as fixed and let spring_layout handle the rest.

    pre_pos = {Huck: (0,0), Christie:(0,1), Graham:(1,1), Bush: (1,2)}
    my_pos = nx.spring_layout(G, pos=pre_pos, fixed = pre_pos.keys())
    nx.draw_networkx(G,pos=my_pos)
    

    Then it will hold the nodes fixed that you've specified in fixed.

    Alternately, define all the positions for just the largest component. Then hold those fixed and add the other nodes. The largest component will "fill" most of the available space, and then I think spring_layout will try to keep the added nodes from being too far away (alternately once you see the layout, you can specify these by hand).

    nodes_of_largest_component  = max(nx.connected_components(G), key = len)
    largest_component = G.subgraph(nodes_of_largest_component)
    pos = nx.spring_layout(largest_component)
    pos = nx.spring_layout(G,pos=pos,fixed=nodes_of_largest_component)
    nx.draw_networkx(G,pos=pos)
    

    One more thing to be aware of is that each call to spring_layout will result in a different layout. This is because it starts with some random positions. This is part of why it's useful to save the position dictionary, particularly if you plan to do anything fancy with the figure.

    0 讨论(0)
提交回复
热议问题