Code Explanation
1. Import Libraries
import networkx as nx
import matplotlib.pyplot as plt
networkx is used for creating and managing graphs
(e.g., family trees).
matplotlib.pyplot is used for visualizing the graph.
2. Create a Graph
G = nx.DiGraph()
DiGraph() creates a Directed Graph where edges have
a direction (e.g., parent to child).
3. Add Nodes (Individuals)
nodes = ['Grandfather', 'Grandmother', 'Father',
'Mother', 'Child 1', 'Child 2']
G.add_nodes_from(nodes)
Nodes represent individuals in the family.
add_nodes_from() efficiently adds multiple nodes at once.
4. Add Edges (Relationships)
edges = [('Grandfather', 'Father'),
('Grandmother', 'Father'),
('Father', 'Child 1'),
('Father', 'Child 2'),
('Mother', 'Child 1'),
('Mother',
'Child 2')]
G.add_edges_from(edges)
Edges represent parent-child relationships using
tuples (Parent, Child).
add_edges_from() adds multiple relationships.
5. Configure and Draw the Graph
plt.figure(figsize=(8, 6))
pos = nx.spring_layout(G)
plt.figure(figsize=(8, 6)) sets the figure size for
better visibility.
nx.spring_layout(G) positions nodes using a force-directed layout, providing a natural and balanced appearance.
nx.draw(G, pos, with_labels=True, node_size=3000, node_color='skyblue', font_size=10, font_weight='bold', edge_color='gray')
nx.draw() renders the graph.
with_labels=True displays the node names.
node_size=3000 controls the size of nodes.
node_color='skyblue' makes the nodes visually distinct.
font_size=10, font_weight='bold' makes the labels more readable.
edge_color='gray' sets the color of the relationships.
6. Add Title and Display the Chart
plt.title('Pedigree Analysis Chart')
plt.show()
plt.title() adds a title to the chart.
plt.show() displays the final output
0 Comments:
Post a Comment