Очистите ваш код следующим образом:
import networkx as nx
from matplotlib import pyplot as plt
track = {(0, 1): 7,
(0, 2): 3,
(1, 4): 6,
(1, 2): 1,
(1, 3): 2,
(2, 3): 2,
(3, 4): 4}
class Draw:
def __init__(self):
self.G=nx.Graph()
def draw(self,node,track):
# node data is a list containing nodes like [0,1,2,3,4]
# track is edge and weight dict like {(0, 1): 7, (0, 2): 3, (1, 4): 6}
[self.G.add_node(k) for k in node]
[self.G.add_edge(k[0],k[1],weight=v) for k,v in track.items()]
# label list data for the weight show
labels = nx.get_edge_attributes(self.G,'weight')
options = {'font_size':20,
'node_color':'red',
'label_pos':0.5,#(0=head, 0.5=center, 1=tail)
'node_size':1200,
'style':'solid',#(solid|dashed|dotted,dashdot)
'width':2}
pos = nx.spring_layout(self.G)
nx.draw(self.G,
pos,
with_labels=True,
**options)
nx.draw_networkx_edge_labels(self.G,
pos,
edge_labels=labels,
**options)
plt.savefig("graph.png")
plt.show()
d = Draw()
d.draw([*range(5)],track)
и вы получите: