This project provides a set of Python functions to visualize graphs and paths within graphs using the Matplotlib and Networkx libraries. The primary functions are showgraph
and showpath
, which are designed to help users visually understand the structure of their graphs and the paths within them.
Ensure you have the required libraries installed:
pip install networkx matplotlib
To use the visualization functions, import them from the respective directory:
from graph_visualizer.visualize import showgraph, showpath
This function visualizes a directed graph.
graph
: A dictionary representing the adjacency list of the graph. Keys are node labels, and values are lists of neighboring nodes.
graph = {
'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['A']
}
showgraph(graph)
Contributions are welcome! To contribute to this project, please follow these steps:
-
Fork the Repository: Click the "Fork" button at the top right corner of this page to create a copy of this repository in your account.
-
Clone the Repository: Clone the forked repository to your local machine using the following command:
git clone https://github.com/advayc/graph-visualizer.git
-
Create a Branch: Create a new branch for your feature or bug fix.
git checkout -b feature-name
-
Make Your Changes: Make your changes to the codebase.
-
Commit Your Changes: Commit your changes with a descriptive commit message.
git commit -m "Add feature-name"
-
Push to the Branch: Push your changes to your forked repository.
git push origin feature-name
-
Create a Pull Request: Navigate to the original repository and create a pull request from your branch.
-
Review Process: Your pull request will be reviewed, and you may be asked to make additional changes before it is merged.
- Graph Creation: A directed graph
G
is created using Networkx'sDiGraph()
class. - Adding Edges: Edges are added to
G
by iterating through the adjacency listgraph
. - Node Colors: Nodes are colored blue by default, with the first node colored red for distinction.
- Layout: The graph layout is calculated using the
spring_layout
algorithm. - Drawing: Nodes and edges are drawn using Networkx's
draw_networkx_nodes
,draw_networkx_edges
, anddraw_networkx_labels
functions. - Displaying: The graph is displayed using Matplotlib's
plt.show()
.
This function visualizes a directed graph with a highlighted path.
graph
: A dictionary representing the adjacency list of the graph. Keys are node labels, and values are lists of neighboring nodes.path
: A list of nodes representing the path to be highlighted.
graph = {
'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['A']
}
path = ['A', 'B', 'D']
showpath(graph, path)
- Graph Creation: A directed graph
G
is created using Networkx'sDiGraph()
class. - Adding Edges: Edges are added to
G
by iterating through the adjacency listgraph
. - Node Colors and Sizes: Nodes are colored blue by default. The starting node is colored green, and the ending node is colored orange. Their sizes are increased for emphasis.
- Layout: The graph layout is calculated using the
spring_layout
algorithm. - Drawing:
- Nodes and edges are drawn using Networkx's
draw_networkx_nodes
,draw_networkx_edges
, anddraw_networkx_labels
functions. - The path edges are highlighted in red.
- Nodes and edges are drawn using Networkx's
- Hover and Click Event Handling:
- A scatter plot is created for hover and click detection.
- An event handler updates the title based on the hovered node.
- Animation:
- An animation is created to showcase the path dynamically using Matplotlib's
FuncAnimation
.
- An animation is created to showcase the path dynamically using Matplotlib's
from graph_representation.visualize import showgraph, showpath
# Define the graph as an adjacency list
graph = {
'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['A']
}
# Visualize the graph
showgraph(graph)
# Define a path to highlight
path = ['A', 'B', 'D']
# Visualize the graph with the highlighted path
showpath(graph, path)
This function creates a visual representation of a directed graph.
-
Graph Creation:
G = nx.DiGraph()
-
Adding Edges:
for node in graph: for neighbor in graph[node]: G.add_edge(node, neighbor)
-
Node Colors:
node_colors = {node: 'tab:blue' for node in G.nodes()} node_colors[list(G.nodes())[0]] = 'tab:red'
-
Layout:
pos = nx.spring_layout(G, seed=3113794652)
-
Drawing:
options = {"edgecolors": "tab:gray", "node_size": 800, "alpha": 0.9} node_color_list = [mcolors.CSS4_COLORS.get(node_colors[node], 'tab:blue') for node in G.nodes()] nx.draw_networkx_nodes(G, pos, node_color=node_color_list, **options) nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5) nx.draw_networkx_labels(G, pos, font_size=12, font_family='sans-serif', font_color="whitesmoke")
-
Displaying:
plt.title('Graph Visualization') plt.axis('off') plt.show()
This function creates a visual representation of a directed graph with a highlighted path.
-
Graph Creation:
G = nx.DiGraph()
-
Adding Edges:
for node in graph: for neighbor in graph[node]: G.add_edge(node, neighbor)
-
Node Colors and Sizes:
node_colors = {node: '#1f77b4' for node in G.nodes()} node_sizes = {node: 800 for node in G.nodes()} starting_node = path[0] ending_node = path[-1] node_colors[starting_node] = '#007300' node_colors[ending_node] = '#ff7f0e' node_sizes[starting_node] = 1000 node_sizes[ending_node] = 1000
-
Layout:
pos = nx.spring_layout(G, seed=3113794652)
-
Drawing:
options = {"edgecolors": "#333333", "alpha": 0.9} node_color_list = [node_colors[node] for node in G.nodes()] node_size_list = [node_sizes[node] for node in G.nodes()] fig, ax = plt.subplots(figsize=(8, 6)) fig = pylab.gcf() fig.canvas.manager.set_window_title('Visualize The Shortest Path in a Unweighted Graph') nx.draw_networkx_nodes(G, pos, node_color=node_color_list, node_size=node_size_list, **options, ax=ax) path_edges = [(path[i], path[i + 1]) for i in range(len(path) - 1)] nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5, ax=ax) nx.draw_networkx_edges(G, pos, edgelist=path_edges, width=2, alpha=0.7, edge_color="#ff3333", ax=ax) nx.draw_networkx_labels(G, pos, font_size=12, font_family='sans-serif', font_color="whitesmoke", ax=ax) plt.title('Graph Visualization with Highlighted Path') plt.axis('off')
-
Hover and Click Event Handling:
def on_hover(event): if event.inaxes == ax: cont, ind = scatter.contains(event) if cont: index = ind['ind'][0] node = list(G.nodes())[index] if node == starting_node: ax.set_title('Hovering over the starting node') elif node == ending_node: ax.set_title('Hovering over the ending node') else: ax.set_title(f'Hovered over node: {node}') fig.canvas.draw_idle() else: ax.set_title('Graph Visualization with Highlighted Path') fig.canvas.draw_idle() scatter = ax.scatter( [pos[node][0] for node in G.nodes()], [pos[node][1] for node in G.nodes()], s=[node_sizes[node] for node in G.nodes()], c=[node_colors[node] for node in G.nodes()], edgecolors=options["edgecolors"], alpha=options["alpha"] ) fig.canvas.mpl_connect('motion_notify_event', on_hover)
-
Animation:
def update(num): ax.clear() nx.draw_networkx_nodes(G, pos, node_color=node_color_list, node_size=node_size_list, **options, ax=ax) nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5, ax=ax) nx.draw_networkx_edges(G, pos, edgelist=path_edges[:num+1], width=2, alpha=0.7, edge_color="#ff3333", ax=ax) nx.draw_networkx_labels(G, pos, font_size=12, font_family='sans-serif', font_color="whitesmoke", ax=ax) plt.title('Graph Visualization with Highlighted Path') plt.axis('off') ani = animation.FuncAnimation(fig, update, frames=len(path_edges)+1, repeat=False, interval=500) plt.show()
These functions provide a straightforward way to visualize graphs and paths within them, making it easier to understand the structure and flow of the graph. By using Networkx and Matplotlib, the visualizations are both informative and customizable.