如何查看在python中使用图生成的网络?

时间:2019-02-10 09:13:55

标签: python matplotlib networkx

我正在尝试生成网络并希望以图形方式查看它。

我正在使用一个列表来存储边缘信息。

我尝试了以下方法:

  from collections import defaultdict
class Graph(object):
    def __init__(self,connections):
        self.graph = defaultdict(set)
        self.addConnections(connections)

    def addConnections(self, connections):
        for node1, node2 in connections:
            self.addEdge(node1, node2)

    def addEdge(self, node1, node2):
        self.graph[node1].add(node2)

    def generateEdges(self): 
        edges = [] 
        for node in self.graph: 
            for neighbour in self.graph[node]: 
                edges.append((node, neighbour))
        self.edges = edges
        return edges

我正在尝试按如下方式查看图形:

import networkx as nx
import matplotlib.pyplot as plt
from graph import Graph
#create edges for first graph
graph1Edges = [('A','B'), ('A', 'D'), ('B', 'C'), ('C','D')]
graph1 = Graph(graph1Edges)
nx.draw(graph1.generateEdges())
plt.show()

但是,它不起作用,请为我建议一种解决方法,因为我不想使用networkx软件包。

1 个答案:

答案 0 :(得分:0)

您试图自己实现一个Graph并使用networkx来显示它,而不是使用networkx的图实现。当然这是不可能的,因为nx.draw需要一个networkx图。

只需删除您的Graph实现并运行:

import networkx as nx
import matplotlib.pyplot as plt

edges = [('A', 'B'), ('A', 'D'), ('B', 'C'), ('C', 'D')]
G = nx.Graph()
G.add_edges_from(edges)
nx.draw_networkx(G)
plt.show()

您会得到:

enter image description here