Skip to content

Instantly share code, notes, and snippets.

@RobertTalbert
Last active October 18, 2022 15:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobertTalbert/728c98a9ac527bab9083474213331e4a to your computer and use it in GitHub Desktop.
Save RobertTalbert/728c98a9ac527bab9083474213331e4a to your computer and use it in GitHub Desktop.
# Code for generating random weighted graphs in networkX and printing off the edges
import networkx as nx
import matplotlib.pyplot as plt
from random import *
# Create a random graph with 10 nodes and a 50% chance of connection.
# Change the 10 and 0.5 for graphs with more/fewer nodes and more/fewer connections.
G = nx.random_graphs.gnp_random_graph(10,.5)
m = G.number_of_edges()
# Assign random weights between 1 and 5 to each edge.
# Change the 1 and 5 for a different range.
weights = [randint(1,5) for r in range(m)]
unweighted_edges = list(G.edges())
weighted_edges = [(unweighted_edges[i][0], unweighted_edges[i][1], {'weight':weights[i]}) for i in range(m)]
newG = nx.Graph(weighted_edges)
# Drawing the graph
pos = nx.circular_layout(newG)
# pos = nx.spring_layout(newG)
nx.draw(newG,pos, with_labels=True, node_color = "cyan") # Added the with_labels = True to show vertex labels
labels = nx.get_edge_attributes(newG, 'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
plt.show()
# Finally, print off the edge list with the weights.
print(newG.edges(data=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment