Skip to content
Graph theory example
!pip install pydot# Import libraries
import networkx as nx # Network analysis
import matplotlib.pyplot as plt # Data visualization
import pydot # Python interface to Graphviz
from networkx.drawing.nx_pydot import graphviz_layout# Create a graph
graph = nx.Graph()
# Add the nodes
# graph.add_node("Alice") --> Add one node per time
graph.add_nodes_from([
"Alice","Bob", "Carol", "Dave"
]) # Add multiple nodes
# Add the edges
# graph.add_edge("Alice", "Bob") --> Add one edge per time
graph.add_edges_from([("Alice", "Bob"),
("Alice", "Carol"),
("Bob", "Dave"),
]) # Add multiple edges
# Visualize the plot
pos = graphviz_layout(graph, prog="dot")
nx.draw(graph,
pos,
with_labels=True,
node_size=1000,
node_color=["pink", "yellow", "tan", "orange"])
plt.show()