Plotting Graphs in Python
Master graph visualization using customized node size and positions in Python using NetworkX.
We'll cover the following...
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, oftenpos
, 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
Here's the complete code for plotting the graph:
Press + to interact
import networkx as nximport matplotlib.pyplot as plt# Create an empty graphG = nx.Graph()# Add nodes to the graph with custom labelsG.add_node("Parent 1")G.add_node("Parent 2")G.add_node("Child 1")G.add_node("Child 2")# Add edges between nodesG.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 nodesnx.draw(G, with_labels=True, node_color="lightblue", node_size=4500, font_weight="bold")# Show the plotplt.savefig('output/FamilyGraph')plt.show()
Line ...