Plotting Graphs in Python

Master graph visualization using customized node size and positions in Python using NetworkX.

Plot a simple graph

To plot the graph, we can use the nx.draw() method from the networkx library.

The nx.draw() function visualizes graphs in NetworkX, where the first parameter is the graph object. The second key parameter, often pos, specifies node positions as a dictionary mapping nodes to (x, y) coordinates.

Let's say we want to plot the following graph using Python:

Press + to interact
Members of the family represented by nodes.
Members of the family represented by nodes.

Here's the complete code for plotting the graph:

Press + to interact
import networkx as nx
import matplotlib.pyplot as plt
# Create an empty graph
G = nx.Graph()
# Add nodes to the graph with custom labels
G.add_node("Parent 1")
G.add_node("Parent 2")
G.add_node("Child 1")
G.add_node("Child 2")
# Add edges between nodes
G.add_edge("Parent 1", "Child 1")
G.add_edge("Parent 1", "Child 2")
G.add_edge("Parent 2", "Child 1")
G.add_edge("Parent 2", "Child 2")
# Draw the graph with larger nodes
nx.draw(G, with_labels=True, node_color="lightblue", node_size=4500, font_weight="bold")
# Show the plot
plt.savefig('output/FamilyGraph')
plt.show()
  • Line ...