문제 설명
NetworkX ‑ 노드 묶기 중지 ‑ 시도된 Scale/K 매개변수 (NetworkX ‑ Stop Nodes from Bunching Up ‑ Tried Scale/K parameters)
대부분 사이에 가장자리가 있는 ~28개의 노드가 있으며 일부는 격리되어 있습니다(가장자리 없음). 고립된 노드는 멋지게 펼쳐져 있지만 연결된 노드는 너무 쌓여서 아무것도 볼 수 없습니다. 다양한 node_sizes, scale 및 k 매개변수를 시도했지만 항상 (거의) 동일한 결과를 제공합니다. 더 나은 보기를 강제하는 방법이 있습니까?
nx.draw_spring(candidateGraph, node_size = 1000, with_labels=True, scale=100, weight=weightVal, k=100)
plt.show( )
참조 솔루션
방법 1:
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.