我使用邻接矩阵创建了图论。我有2个类,这使我可以放置每个节点的加油站数量,并且我将边缘/权重用作距离。
现在,我想使用networkx库将其绘制在图形上,但似乎无法找到解决方法。
这是我的代码:
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
class Graph:
def __init__(self):
self.nodes = {}
self.edges = {}
def addNode(self, node, chargers = 0): # adds unique node to graph
if str(node) not in self.nodes:
self.nodes[str(node)] = Node(str(node), chargers)
def addEdge(self, start, end, distance): # if both nodes exist in graph, adds the unique edge
if str(start) in self.nodes and str(end) in self.nodes and f'{min(start, end)}-{max(start, end)}' not in self.edges:
self.edges[f'{min(start, end)}-{max(start, end)}'] = Edge(str(start), str(end), distance)
self.nodes[str(start)].addNeighbor(str(end))
self.nodes[str(end)].addNeighbor(str(start))
def __str__(self): # for Graph object printing
nodes_string = "".join('\n\t' + str(x) for x in self.nodes.values())
edges_string = "".join('\n\t' + str(x) for x in self.edges.values())
return f'Nodes: {nodes_string}\nEdges: {edges_string}'
def adjacency_matrix(self): # returns an binary adjacency matrix, in order of the node names entered
return [[1 if key2 in self.nodes[key1].neighbors else 0 for key2 in self.nodes] for key1 in self.nodes]
class Node:
def __init__(self, name, chargers = 0):
self.name = name
self.chargers = chargers
self.neighbors = []
def addNeighbor(self, neighbor): # adds neighboring nodes names connected by an edge
self.neighbors.append(neighbor)
def __str__(self): # for Node object printing
return f'{self.name} - {self.chargers} - Connected to: {self.neighbors}'
class Edge:
def __init__(self, start, end, distance):
self.start_node = str(start)
self.end_node = str(end)
self.distance = distance
def __str__(self): # for Edge object printing
return f'{self.start_node} -> {self.end_node}: {self.distance} km'
# graph initialization
graph=Graph()
#Here we add nodes and chargers!
graph.addNode('Pristina', 10)
graph.addNode('Lipjan', 167)
graph.addNode('Obiliq', 167)
#Here we add wights/distances!
graph.addEdge('Pristina', 'Obiliq', 1.9)
graph.addEdge('Pristina', 'Lipja', 10.1)
graph.addEdge('Lipjan', 'Obiliq', 14)
print(graph)
print("\nAdjacency Matrix")
print(*graph.adjacency_matrix(), sep = '\n')
我知道只有很少的代码可以将其绘制在图形上,有人可以在这里帮助我吗?