In Python, the way you represent a graph affects what you can learn from it. How you draw it matters too, especially when someone else needs to follow the relationships and understand the result of an analysis. In this article, we’ll build and visualize a graph, then look at the decisions that matter when graphs become larger or their data changes.
What is Python Graph Visualization?
Python graph visualization uses Python to turn connected data into a diagram or interactive view. A graph represents entities as nodes (also called vertices) and relationships as edges (or links). The visualization assigns positions to those nodes and uses labels, color, or other visual properties to make the structure easier to inspect.
The same node-and-edge model can represent different kinds of relationships. In a recommendation system, edges may connect users to items; in bioinformatics, they may record interactions among proteins. A social network shows connections between people, while a logistics network can map routes between locations. Seeing those relationships together makes paths and closely connected groups easier to examine and can draw attention to an unusual connection that warrants investigation. Whether that connection is significant depends on the data behind it.

An undirected graph drawing of a crime network.
Types of Graphs
- Directed graphs: Edges have a direction. A hyperlink from one web page to another, for example, does not imply a link back. Arrows in the drawing show which way each connection runs.
- Undirected graphs: Edges have no direction. Mutual friendships in a social network can be modeled with one connection between each pair of people.
- Weighted graphs: Edges carry a numerical value, such as distance, cost, or capacity. In a transportation network, a route between two cities might be weighted by its length. Labels or visual styling can show the values, provided their meaning is clear to the reader.
- Unweighted graphs: Edges record whether a connection exists without assigning it a numerical weight. A route map modeled this way shows which locations are connected while leaving distances aside.
Direction and weight describe separate properties of a graph. A road network, for example, can use directed edges for one-way streets and weights for travel time.
Representing and Drawing a Graph in Python
A graph data structure can be represented in Python as an adjacency list, which records the neighbors of each node, or as an adjacency matrix, which records connections between pairs of nodes in rows and columns. An adjacency list is compact for a network with relatively few connections. A dense matrix also reserves space for pairs with no edge, but it can be useful for calculations that rely on matrix operations.
The example below uses a NetworkX DiGraph to store directed routes and their travel times. Those weights are used to calculate the shortest path, while the drawing uses arrows to show direction and red edges to highlight the result.
import matplotlib.pyplot as plt
import networkx as nx
routes = nx.DiGraph()
routes.add_weighted_edges_from([
("Depot", "Hub", 4),
("Depot", "Junction", 8),
("Hub", "Junction", 2),
("Hub", "Site", 8),
("Junction", "Site", 3),
])
path = nx.shortest_path(routes, "Depot", "Site", weight="weight")
path_edges = set(zip(path, path[1:]))
positions = nx.spring_layout(routes, seed=7, weight=None)
edge_colors = [
"#b91c1c" if edge in path_edges else "#94a3b8"
for edge in routes.edges()
]
nx.draw_networkx(
routes, positions, with_labels=True, arrows=True,
node_size=2600, node_color="#dbeafe", edge_color=edge_colors
)
nx.draw_networkx_edge_labels(
routes, positions,
edge_labels=nx.get_edge_attributes(routes, "weight")
)
plt.axis("off")
plt.show()
The selected route is Depot → Hub → Junction → Site, with a total travel time of nine minutes. When you run the code, you can compare the selected path with the other available routes and inspect the direction and travel time of each connection. For a detailed comparison of tools for static figures and interactive views, see the Python graph visualization libraries guide.
Advanced Graph Visualization Techniques
A large graph can be difficult to interpret even when Python can process it efficiently. The challenge is deciding which relationships to show, how to arrange them, and what users need to inspect in detail.
Visualizing Large Graphs Efficiently
In a social network, a community detection algorithm can identify groups whose members are more closely connected to one another. Finding those groups does not automatically make a large network easier to read. The visualization needs to show how the groups relate and let an analyst open one for closer inspection.

A graph drawing with clustering algorithm applied.
Dynamic and Real-Time Graph Visualizations
In network monitoring, devices and connections may change while an analyst is viewing the graph. The application needs to receive those changes, update the underlying graph, and refresh the display at a useful rate. A Dash application can use Plotly to display an updated network alongside other operational views, but the data pipeline and update logic must be built as part of the application. Frequent updates also need care: if every change rearranges the whole drawing, users can lose track of the devices they were following.
Customizing Interactive Features
Interaction is most useful when it answers a specific question. A tooltip can show a node’s properties without filling the drawing with labels. Selecting a node might reveal its immediate connections, display statistics, or open a related document. Zooming and panning help users navigate a large drawing, while filtering or opening a subgraph controls how many relationships they must examine at once. Together, these choices determine whether the graph remains useful beyond its initial overview.
Visualizing Graph Algorithm Results
The route calculated in the previous example is a small shortest-path problem. GPS navigation and network routing use the same principle on larger graphs, where direction and edge weights may affect the selected route. Showing the selected path within the surrounding network lets an analyst inspect the route and the other available connections.

A graph of locations with the shortest path algorithm applied.
A minimum spanning tree answers a different question in network design. Given a connected, undirected graph whose edge weights represent costs, it selects connections that reach every node with the lowest possible total weight. The original network may contain cycles; the selected tree does not. Drawing both makes it easier to see which connections the algorithm retained and how the proposed network differs from the available options.
These views also help when teaching or developing graph algorithms: the selected edges can be examined alongside the original structure and its weights, rather than treated as an unexplained output.
Graph Database Visualization
A graph database stores entities and their relationships so they can be queried together. In a Python visualization, the first decision is which part of that graph to retrieve. A focused query gives the drawing a clear purpose and keeps it readable as the database grows.
With Neo4j, a Python application can run a Cypher query and use the returned nodes and relationships to build a view. A query focused on a selected entity and its immediate connections gives the application a manageable subgraph to display.
Amazon Neptune supports property graphs queried with Gremlin or openCypher, as well as RDF graphs queried with SPARQL. A Python application must retrieve data using the query language appropriate to the graph model before arranging the results for display. This is particularly useful for knowledge graphs, where the relationships returned by a query provide context for the entities being examined.
Use Cases for Python Graph Visualization
Python graph visualization is applicable across various domains, providing valuable insights into complex data structures. Here are some key use cases:
Knowledge Graphs: Visualizing knowledge graphs helps in understanding the relationships between different entities, providing insights into the structure of the knowledge base. This is crucial for applications in research, where visualizing the interconnections between concepts can lead to new discoveries and deeper understanding. Implementing Python graph visualization techniques in knowledge graphs makes it easier to manage and explore vast amounts of interconnected data.
Network Analysis: Visualizing network data stored in graph databases can help analyze the structure and interactions within the network. It allows for identifying key nodes and understanding overall connectivity, which is vital in fields like telecommunications, social network analysis, and transportation planning. Effective Python graph visualization of network data can reveal crucial insights and enhance decision-making processes.
Fraud Detection: Visualizing transaction data in graph databases can help detect patterns of fraudulent activity. By examining the connections and interactions between different entities, anomalies can be spotted, providing insights that can lead to the prevention of fraud. This is particularly valuable in financial services and e-commerce. Utilizing Python graph visualization for fraud detection allows for the clear identification of suspicious patterns and connections, aiding in timely and effective intervention.
Best Practices for Python Graph Visualization
Check the drawing against the data before refining its appearance. In the route example, arrows should follow the direction of each connection, edge labels should show the travel times used in the calculation, and the highlighted path should match the algorithm’s result. Use colors and shapes consistently when they represent node types or selected edges. Keep the initial labels focused on what readers need to understand.
Test with a graph that resembles the real dataset, including its densest areas and longest labels. If the view becomes slow, measure analysis, layout, and rendering separately. Graph-tool may help with computationally demanding analysis, while filtering or grouping addresses how much of the network appears at once. When showing groups, retain the connections between them that matter to the question.
For an interactive view, check what happens after a user selects a node, opens a tooltip, or zooms into one part of the graph. Each action should reveal useful detail, and users should have a clear way back to the wider network.
Conclusion
Python can carry a graph from its data structure through analysis to a drawing that people can inspect. In the route example, edge direction and travel time determine the shortest path; the visualization shows that result alongside the other available connections. For a separate, undirected network, a minimum spanning tree answers a different question: which connections reach every location at the lowest total cost. The value of either drawing depends on whether it accurately represents the underlying relationships.
The same approach applies to other kinds of data. Social networks can be examined for communities, while business networks may reveal dependencies between organizations or systems. Transportation routes depend on direction and distance; molecular networks depend on the meaning of their recorded interactions. A useful visualization makes those relationships clear enough to investigate further.
About the Author
Caroline Scharf, VP of Operations at Tom Sawyer Software, has 15 years experience with Tom Sawyer Software in the graph visualization and analysis space, and more than 25 years leadership experience at large and small software companies. She has a passion for process and policy in streamlining operations, a solution-oriented approach to problem solving, and is a strong advocate of continuous evaluation and improvement.
Frequently Asked Questions About Python Graph Visualization
How Do I Visualize a Directed Graph in Python?
Create a directed graph with nx.DiGraph() and add each edge in the direction the relationship follows. After calculating node positions, draw the edges with arrows. If the edges also have values such as distance or travel time, those values can be displayed as labels or used in a path calculation.
Which Python Libraries Support Hierarchical Graph Layouts, and When Should I Use Them?
Graphviz’s dot engine calculates layered layouts for directed graphs. NetworkX can use Graphviz to obtain node positions, while graph-tool provides layouts for trees and hierarchies. Pyvis has a hierarchical layout option, while Plotly can display a network using node positions calculated with another tool. A hierarchical layout is useful when the data has meaningful levels, as in an organizational chart, taxonomy, or workflow.
How Can I Update a Python Graph Visualization as Data Changes?
A Dash application can refresh a Plotly view at intervals through a callback; Bokeh server applications also support periodic callbacks. The application still needs to receive new data, change the graph, and refresh the display. Pyvis supports interactive exploration, but a live data feed and update process must be built separately.
How Can I Visualize 3D Graphs in Python, and When Is It Useful?
Plotly can draw nodes and edges in three dimensions, while pythreejs can create an interactive 3D scene in Jupyter. A 3D view is most useful when spatial position is part of the data, as it can be for molecular structures or geographic networks with elevation. For a dense social graph, test whether 3D makes the connections clearer than a 2D drawing.
How Do Python Graph Visualization Libraries Display Shortest Paths and Minimum Spanning Trees?
NetworkX, graph-tool, and igraph can calculate both results. Shortest-path methods, including Dijkstra’s and Bellman-Ford’s algorithms, find a route between selected nodes. Minimum spanning tree methods, such as Prim’s and Kruskal’s, connect all nodes in an undirected network while minimizing total edge weight. The selected edges can then be highlighted in a static Matplotlib figure or an interactive Pyvis view.
How Can I Use Python Graph Analysis with Tom Sawyer Perspectives?
Python can prepare graph data and calculate results such as paths or communities. That data can be exported in a suitable format, such as JSON or CSV, and mapped into Tom Sawyer Perspectives through a configured integration. Perspectives can then provide graph layouts, interactive views, and analysis in an application built for its users.
Submit a Comment