使用Networkx绘制带边的图形

时间:2012-10-28 21:23:12

标签: python graph edge networkx

我一直很困扰一些非常简单的事情。我正在尝试绘制并显示包含2个节点和1个边缘的图形。但是我得到了这个错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/networkx/drawing/nx_pylab.py", line 133, in      draw
draw_networkx(G,pos=pos,ax=ax,**kwds)
File "/usr/local/lib/python2.7/site-packages/networkx/drawing/nx_pylab.py", line 267, in draw_networkx
edge_collection=draw_networkx_edges(G, pos, **kwds)
File "/usr/local/lib/python2.7/site-packages/networkx/drawing/nx_pylab.py", line 546, in draw_networkx_edges
ax.add_collection(edge_collection)
File "/usr/local/lib/python2.7/site-packages/matplotlib/axes.py", line 1445, in add_collection
self.update_datalim(collection.get_datalim(self.transData))
File "/usr/local/lib/python2.7/site-packages/matplotlib/collections.py", line 167, in get_datalim
offsets.shape = (-1, 2)                     # Make it Nx2
AttributeError: incompatible shape for a non-contiguous array

非常简单,我只需添加2个节点

add_node(1) 
add_node(2)
add_edge(1,2)

然后绘制并显示它。但我无法让它发挥作用。

2 个答案:

答案 0 :(得分:2)

import networkx as nx
g=nx.Graph()
g.add_node(1)
g.add_node(2)
g.add_edge(1,2)
nx.draw(g)

答案 1 :(得分:2)

这是一个有效的解决方案。

import matplotlib.pyplot as plt
import networkx as nx

# Create a basic Graph
g=nx.Graph()
g.add_node(1)
g.add_node(2)
g.add_edge(1,2)

# Output the result
nx.draw(g)
plt.show()