|
1 |
| -import random |
2 | 1 | import networkx as nx
|
3 | 2 | import matplotlib.pyplot as plt
|
| 3 | +import numpy as np |
4 | 4 |
|
5 |
| -# Create a graph |
6 |
| -G = nx.Graph() |
7 |
| -G.add_nodes_from(range(10)) |
8 |
| -G.add_edges_from([(0,1), (1,2), (2,3), (3,4), (4,5), (5,6), (6,7), (7,8), (8,9), (9,0)]) |
| 5 | +# Create a random graph with 10,000 nodes and 50,000 edges |
| 6 | +G = nx.gnm_random_graph(1000, 5000) |
9 | 7 |
|
10 |
| -# Set random colors for nodes and edges |
11 |
| -node_colors = [random.choice(['red', 'blue', 'green']) for _ in range(len(G.nodes()))] |
12 |
| -edge_colors = [random.choice(['red', 'blue', 'green']) for _ in range(len(G.edges()))] |
| 8 | +# Set random weights for the edges |
| 9 | +weights = np.random.rand(len(G.edges)) |
| 10 | +nx.set_edge_attributes(G, dict(zip(G.edges, weights)), 'weight') |
13 | 11 |
|
14 |
| -# Draw the graph with node and edge colors |
15 |
| -nx.draw(G, with_labels=True, node_color=node_colors, edge_color=edge_colors) |
| 12 | +# Generate a layout using the spring layout algorithm |
| 13 | +pos = nx.spring_layout(G) |
| 14 | + |
| 15 | +# Assign colors to the nodes based on their degree |
| 16 | +node_colors = np.array(list(dict(G.degree()).values())) |
| 17 | +node_colors = (node_colors - node_colors.min()) / (node_colors.max() - node_colors.min()) |
| 18 | + |
| 19 | +# Assign colors to the edges based on their weight |
| 20 | +edge_weights = nx.get_edge_attributes(G, 'weight') |
| 21 | +edge_weights_norm = (np.array(list(edge_weights.values())) - min(edge_weights.values())) / (max(edge_weights.values()) - min(edge_weights.values())) |
| 22 | +cmap = plt.cm.get_cmap('Blues') |
| 23 | +edge_colors = cmap(edge_weights_norm) |
| 24 | + |
| 25 | +# Draw the graph using the layout and color scheme |
| 26 | +nx.draw(G, pos=pos, node_color=node_colors, edge_color=edge_colors, with_labels=False, node_size=5, width=0.5) |
| 27 | + |
| 28 | +# Add a title and subtitle to the plot |
| 29 | +plt.title("Random Graph with 10,000 Nodes and 50,000 Edges") |
| 30 | +plt.suptitle("Generated using the gnm_random_graph() function from NetworkX") |
| 31 | + |
| 32 | +# Display the plot |
16 | 33 | plt.show()
|
0 commit comments