无法将边缘添加到networkx图

时间:2020-04-17 12:18:18

标签: python visualization networkx graph-theory

所以我以前从未使用过Networkx,所以这可能是基本的。我目前正在使用几个函数来输出简单图形的字典,例如循环图。例如,如果我为n = 5运行该函数,我将得到字典:{1:[5,2],2:[1,3],3:[2,4],4:[3,5], 5:[4,1]}。

我已经开始尝试使用Networkx可视化这些内容,并具有以下功能来输出图形的边缘:

def generate_edges(graph): # generate edges of the graph

    edges = []

    for node in graph: # checks each node

        for neighbour in graph[node]:

            edges.append((node,neighbour)) # returns the node,neighbour pair as an edge

    return edges

然后我使用以下功能来创建网络可视化:

def visualise(graph):

    edges = generate_edges(graph)
    nodes = list(graph.keys())

    G = nx.graph
    G.add_edges_from(edges)
    G.nodes(data=True)
    nx.write_graphml(G,'so.graphml')
    print(nx.info(G))

    return G

graph = generate_simplegraph('cycle',10)
visualise(graph)

其中“周期”是图形的类型,而10是节点的数量。我不断收到错误消息:

模块'networkx.classes.graph'没有属性'add_edges_from'

有人可以告诉我为什么会出现此错误以及如何解决该错误吗?我要做的就是可视化网络。另外,我将networkx导入为nx。

1 个答案:

答案 0 :(得分:1)

我相信

graph应该是networkx中的一类。

G=nx.Graph()

不是:

G = nx.graph