Draw a graph with edges using Networkx

2019-05-28 16:54发布

I've been troubled by something very simple. I am trying to draw and show a graph with 2 nodes and 1 edge. But I get this error:

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

It is very simple, I just add 2 nodes with

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

and then draw it and show it. But I just cant get it to work.

2条回答
爷的心禁止访问
2楼-- · 2019-05-28 17:12
import networkx as nx
g=nx.Graph()
g.add_node(1)
g.add_node(2)
g.add_edge(1,2)
nx.draw(g)
查看更多
混吃等死
3楼-- · 2019-05-28 17:13

Here is a solution that works.

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()
查看更多
登录 后发表回答