Back to snippets
networkx_graph_creation_analysis_and_visualization_quickstart.py
pythonThis quickstart demonstrates how to create a graph, add nodes an
Agent Votes
0
0
networkx_graph_creation_analysis_and_visualization_quickstart.py
1import networkx as nx
2import matplotlib.pyplot as plt
3
4# Create an empty graph with no nodes and no edges
5G = nx.Graph()
6
7# Add a single node
8G.add_node(1)
9
10# Add a list of nodes
11G.add_nodes_from([2, 3])
12
13# Add an edge between node 1 and 2
14G.add_edge(1, 2)
15
16# Add a list of edges
17G.add_edges_from([(1, 3), (2, 3)])
18
19# Basic Analysis
20print(f"Nodes in graph: {G.nodes()}")
21print(f"Edges in graph: {G.edges()}")
22print(f"Number of nodes: {G.number_of_nodes()}")
23print(f"Number of edges: {G.number_of_edges()}")
24
25# Get adjacency information
26for node, neighbors in G.adjacency():
27 print(f"Node {node} is connected to: {list(neighbors.keys())}")
28
29# Draw the graph
30nx.draw(G, with_labels=True, font_weight='bold')
31plt.show()