我正在尝试通过networkx绘制图形。但是,以下代码会遇到错误
NetworkXError:节点8没有位置
我相信只允许少于7个节点,但我不明白为什么。
请说明错误发生的原因以及如何修复以绘制超过8个节点。
import networkx as nx
# new_words = ["1","2","3","4","5","6","7"] => It does not occur the error
new_words = ["1","2","3","4","5","6","7","8"]
target_word = ["0"]
G=nx.cubical_graph()
pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,
nodelist=[0],
node_color='r',
node_size=50, alpha=0.8)
nx.draw_networkx_nodes(G,pos,
nodelist=range(1, len(new_words)+1),
node_color='w',
node_size=50, alpha=0.8)
nx.draw_networkx_edges(G,pos,
edgelist=[(0,i) for i in range(1,len(new_words)+1)])
# some math labels
labels={}
labels[0]=target_word
for idx in range(0,len(new_words)):
labels[idx+1] = new_words[idx]
nx.draw_networkx_labels(G,pos,labels)
错误消息是:
---------------------------------------------------------------------------
NetworkXError Traceback (most recent call last)
<ipython-input-16-5ddab3dbe0d6> in <module>()
15 nodelist=range(1, len(new_words)+1),
16 node_color='w',
---> 17 node_size=50, alpha=0.8)
18
19 nx.draw_networkx_edges(G,pos,
/Users/sudou/.pyenv/versions/anaconda-2.0.1/lib/python2.7/site-packages/networkx/drawing/nx_pylab.pyc in draw_networkx_nodes(G, pos, nodelist, node_size, node_color, node_shape, alpha, cmap, vmin, vmax, ax, linewidths, label, **kwds)
384 xy = numpy.asarray([pos[v] for v in nodelist])
385 except KeyError as e:
--> 386 raise nx.NetworkXError('Node %s has no position.'%e)
387 except ValueError:
388 raise nx.NetworkXError('Bad value in node positions.')
NetworkXError: Node 8 has no position.
答案 0 :(得分:1)
nx.cubical_graph()
有8个节点。即[0,1,2,3,4,5,6,7]
。您已发送包含节点nodelist
的{{1}},该节点不属于您的图表。您绘制的图形是立方体的图形 - 8个节点(顶点)和12个边缘(立方体的边缘)。
您要求它绘制8个节点图的9个节点。因此,它无法找到该节点的位置。
回答关于如何在图表中绘制超过8个节点的问题,您必须从包含8个以上节点的图表开始。