The draw module provides visualization tools for various data structures using NetworkX and Matplotlib. Each data structure has a dedicated draw class that can render, save, and display visual representations.
All draw classes inherit from the base Draw class and provide consistent draw(), save(), and render() methods.
All visualization classes inherit from the Draw base class.
draw.py:10
class Draw: """ A base class for drawing various data structures. This class provides basic functionalities for rendering, saving, and displaying visual representations of data structures. """
def save(self, filename, **kwargs): """ Save the rendered plot to a file. Args: filename (str): The name of the file to save the plot to. **kwargs: Additional keyword arguments. """
class TreeDraw(Draw): """ A class for drawing a tree structure using the NetworkX library. This class extends the `Draw` class to visualize tree structures. It organizes the nodes in a hierarchical tree layout and provides options for customization through the `render` method. Attributes: tree (Tree): The tree structure to be drawn. Usage Example: t = Tree(root_node) # Define your tree structure with a root node td = TreeDraw(t) td.draw() """
class HeapDraw(Draw): """ A class for drawing a heap structure using the NetworkX library. This class extends the `Draw` class to visualize heap structures, such as binary heaps or min-heaps. Attributes: heap (Heap): The heap structure to be drawn. Usage Example: h = MinHeap() # Define your heap, e.g., MinHeap or Heap hd = HeapDraw(h) hd.draw() """
def __init__(self, heap: Heap, **kwargs): """ Initializes the HeapDraw object. Args: heap (Heap): The heap structure to be drawn. **kwargs: Additional keyword arguments passed to the parent `Draw` class. """
from dsa.heap import MinHeapfrom dsa.draw import HeapDraw# Create and populate a min-heapheap = MinHeap()values = [5, 3, 7, 1, 9, 4, 6]for val in values: heap.insert(val)# Visualize the heaphd = HeapDraw(heap)hd.draw()# Save to filehd.save("heap.png")
The heap is automatically converted to a tree structure for visualization using the array_to_node() helper method (draw.py:164-187).
class TrieDraw(Draw): """ A class for drawing a Trie structure using the NetworkX library. This class extends the `Draw` class to visualize Trie structures, commonly used for storing strings or prefix trees. It provides methods to convert the Trie into a networkx graph, arrange nodes hierarchically, and render the visualization using Matplotlib. Attributes: trie (Trie): The Trie structure to be drawn. Usage Example: trie = Trie() # Initialize your Trie and populate it with words trd = TrieDraw(trie) trd.draw() """
def __init__(self, trie: Trie, **kwargs): """ Initializes the TrieDraw object. Args: trie (Trie): The Trie structure to be drawn. **kwargs: Additional keyword arguments passed to the parent `Draw` class. """
from dsa.trie import Triefrom dsa.draw import TrieDraw# Create and populate a trietrie = Trie()words = ["cat", "car", "card", "dog", "dodge", "door"]for word in words: trie.insert(word)# Visualize the trietd = TrieDraw(trie)td.set_figsize((12, 8))td.draw()# Save to filetd.save("trie.png")
The TrieDraw class also provides a rectangle-based rendering method:
draw.py:310
def render_rectangle(self, **kwargs): """ Renders the Trie as a hierarchical graph using Matplotlib. Not to be called directly. Call draw() instead. This method uses the hierarchical positions of the nodes to render the Trie as a directed graph. Nodes are drawn as rectangles, and edges represent the transitions between prefixes. Returns: matplotlib.pyplot: The Matplotlib plot object for further customization or display. """
class GraphDraw(Draw): """ A class for drawing graphs using the NetworkX library. This class extends the `Draw` class to visualize graphs. It supports both directed and undirected graphs, as well as weighted and unweighted graphs. Additionally, it provides an option to display the Minimum Spanning Tree (MST) of the graph. If directed or weighted parameters are not provided, they will be inferred from the graph type. Attributes: graph: The graph to be drawn directed (bool): Specifies if the graph is directed. Defaults to None weighted (bool): Specifies if the graph has weighted edges. Defaults to None Usage Example: gd = GraphDraw(g) # g is a Graph type (AdjacencyMatrixGraph, AdjacencyMatrixWeightedGraph, AdjacencyListWeightedGraph, AdjacencyListGraph) gd.draw() """
def render(self, pos=None, show_mst=False, mst_only=False, **kwargs): """ Renders the graph using Matplotlib. Not to be called directly. Call draw() instead. """
Parameters:
pos (dict, optional): Custom node positions
show_mst (bool): Highlight the minimum spanning tree in red
mst_only (bool): Show only the MST edges (automatically sets show_mst=True)
from dsa.graph import AdjacencyListWeightedGraphfrom dsa.draw import GraphDraw# Create a weighted graphgraph = AdjacencyListWeightedGraph()graph.add_edge('A', 'B', 4)graph.add_edge('A', 'C', 2)graph.add_edge('B', 'C', 1)graph.add_edge('B', 'D', 5)graph.add_edge('C', 'D', 8)# Visualize with edge weightsgd = GraphDraw(graph)gd.set_figsize((10, 8))gd.draw()
3
Visualize Minimum Spanning Tree
from dsa.graph import AdjacencyListWeightedGraphfrom dsa.draw import GraphDraw# Create a weighted graphgraph = AdjacencyListWeightedGraph()graph.add_edge('A', 'B', 4)graph.add_edge('A', 'C', 2)graph.add_edge('B', 'C', 1)graph.add_edge('B', 'D', 5)graph.add_edge('C', 'D', 8)graph.add_edge('C', 'E', 10)graph.add_edge('D', 'E', 2)# Show graph with MST highlighted in redgd = GraphDraw(graph)gd.draw(show_mst=True)# Or show only the MSTgd.draw(mst_only=True)
4
Directed graph visualization
from dsa.graph import AdjacencyListGraphfrom dsa.draw import GraphDraw# Create a directed graphgraph = AdjacencyListGraph()graph.add_edge('A', 'B', directed=True)graph.add_edge('B', 'C', directed=True)graph.add_edge('C', 'D', directed=True)graph.add_edge('D', 'A', directed=True)# Visualize with arrowsgd = GraphDraw(graph)gd.draw()
# Default sizes vary by data structuretd = TreeDraw(tree)td.set_figsize((12, 8)) # Larger for complex treeshd = HeapDraw(heap)hd.set_figsize((10, 6)) # Medium for heapstd = TrieDraw(trie)td.set_figsize((14, 10)) # Large for tries with many words
from dsa.draw import GraphDrawgd = GraphDraw(graph)gd.set_figsize((16, 12))# Save with high DPI for publicationsimport matplotlib.pyplot as pltplt = gd.render()plt.savefig("graph_hq.png", dpi=300, bbox_inches='tight')