Skip to content

Instantly share code, notes, and snippets.

@KenoLeon
Created June 3, 2022 01:56
Show Gist options
  • Select an option

  • Save KenoLeon/8640482bb3cc200fbdd5c319a0197a89 to your computer and use it in GitHub Desktop.

Select an option

Save KenoLeon/8640482bb3cc200fbdd5c319a0197a89 to your computer and use it in GitHub Desktop.
Two town graph with weight in netowrkx
import networkx as nx
import matplotlib.pyplot as plt
# Simple Two Town graph in networkx with weight data
# Init A Graph in networkx
G = nx.Graph()
# Townspeople and towns
KimberleyTown = ['Alice', 'Bob', 'Cathy', 'Dan',
'Ed', 'Fred', 'Gail', 'Hal', 'Ike', 'John']
WordenTown = ['Kim', 'Liz', 'Mike', 'Ned', 'Olivia',
'Pete', 'Quinn', 'Ralph', 'Sally', 'Ted', 'Uma']
Towns = ['KimberleyTown', 'WordenTown']
# Add nodes to graph from twoTowns
G.add_node(Towns[0])
G.add_node(Towns[1])
# The road connecting two towns
G.add_edge(Towns[0], Towns[1], weight=2)
# Add townspeople
for i in range(len(KimberleyTown)):
G.add_edge(Towns[0], KimberleyTown[i], weight=1)
for i in range(len(WordenTown)):
G.add_edge(Towns[1], WordenTown[i], weight=1)
# Plot graph
fig = plt.figure(0)
fig.canvas.set_window_title('2 Towns')
# Get node position:
pos = nx.spring_layout(G)
# print(pos)
nx.draw(G, with_labels=True, node_size=200, node_color='#A0CBE2',
horizontalalignment='left', verticalalignment='top',
font_size=10, font_color='#000000', font_weight='bold',
font_family='sans-serif')
# get edge data
labels = nx.get_edge_attributes(G, 'weight')
# draw edge data
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment