How to Create a Network Graph with X and Y Coordinates in Python?

Estimated read time 2 min read

To create a network graph with X and Y coordinates in Python, you can use the networkx and matplotlib libraries. Here’s an example:

import networkx as nx
import matplotlib.pyplot as plt

# Create a graph
G = nx.Graph()

# Add nodes
G.add_node('A', pos=(0,0))
G.add_node('B', pos=(1,1))
G.add_node('C', pos=(1,-1))
G.add_node('D', pos=(-1,1))
G.add_node('E', pos=(-1,-1))

# Add edges
G.add_edge('A', 'B')
G.add_edge('A', 'C')
G.add_edge('B', 'C')
G.add_edge('B', 'D')
G.add_edge('C', 'E')
G.add_edge('D', 'E')

# Get positions of nodes
pos = nx.get_node_attributes(G, 'pos')

# Draw graph
nx.draw(G, pos)
labels = nx.draw_networkx_labels(G, pos)

# Show graph

In this example, we create a graph with nodes A, B, C, D, and E, and edges connecting them. We add X and Y coordinates to each node using the pos attribute. We then get the positions of each node using the get_node_attributes method and draw the graph using the draw method. Finally, we add labels to the nodes using the draw_networkx_labels method and show the graph using

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply