{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Interactive Network Visualization\n",
        "\n",
        "## Common Use Cases for interactive network visualizations\n",
        "\n",
        "-   social networks\n",
        "-   knowledge graphs\n",
        "-   dependency graphs\n",
        "-   recommender systems\n",
        "-   biological interaction networks\n",
        "\n",
        "## Common libraries comparison\n",
        "\n",
        "| Library        | Best for                      | Scale        | Ease      |\n",
        "|----------------|-------------------------------|--------------|-----------|\n",
        "| **PyVis**      | quick interactive graphs      | medium       | very easy |\n",
        "| **Plotly**     | dashboards & polished visuals | medium       | medium    |\n",
        "| **Bokeh**      | custom web apps               | medium-large | harder    |\n",
        "| **Graphistry** | huge graphs                   | very large   | medium    |\n",
        "| **Netwulf**    | research exploration          | small-medium | very easy |\n",
        "\n",
        "# PyVis\n",
        "\n",
        "`Vis.js` is a lightweight browser library for highly interactive network\n",
        "visualizations that powers many Python tools such as PyVis.\n",
        "\n",
        "**Install**: `conda install -c conda-forge pyvis`\n",
        "\n",
        "## Overview\n",
        "\n",
        "-   PyVis is one of the easiest ways to create **interactive** graph\n",
        "    visualizations directly in Python.\n",
        "\n",
        "Key features\n",
        "\n",
        "-   Built on `Vis.js` physics engine\n",
        "\n",
        "-   Pan / zoom / drag nodes\n",
        "\n",
        "-   Hover tooltips and clickable nodes\n",
        "\n",
        "-   Works directly with NetworkX\n",
        "\n",
        "-   Generates interactive HTML graphs\n",
        "\n",
        "## What is Vis.js?\n",
        "\n",
        "**What it is**\n",
        "\n",
        "A browser-based **JavaScript visualization library** for building\n",
        "**interactive network graphs and timelines**. Widely used as the\n",
        "rendering engine behind tools like **PyVis**.\n",
        "\n",
        "### Core Capabilities\n",
        "\n",
        "**Interactive graph exploration**\n",
        "\n",
        "-   Drag nodes\n",
        "-   Pan / zoom\n",
        "-   hover tooltips\n",
        "-   selectable nodes and edges\n",
        "\n",
        "**Physics-based layouts**\n",
        "\n",
        "-   force-directed graph simulation\n",
        "-   automatic node positioning\n",
        "-   adjustable repulsion / attraction parameters\n",
        "\n",
        "**Dynamic graph updates**\n",
        "\n",
        "-   add/remove nodes in real time\n",
        "-   animate transitions\n",
        "-   update graph without full redraw\n",
        "\n",
        "## Network Visualization Model\n",
        "\n",
        "Graph defined by two main objects:\n",
        "\n",
        "    nodes = [{id:1,label:\"A\"}, {id:2,label:\"B\"}]\n",
        "\n",
        "    edges = [{from:1,to:2}]\n",
        "\n",
        "Rendered with\n",
        "\n",
        "    new vis.Network(container, {nodes, edges}, options)\n",
        "\n",
        "## PyVis Key Features\n",
        "\n",
        "**Highly interactive**\n",
        "\n",
        "-   node dragging\n",
        "-   hover events\n",
        "-   clickable links\n",
        "\n",
        "**Layout options**\n",
        "\n",
        "-   physics layout (force-directed)\n",
        "-   hierarchical layout\n",
        "-   fixed coordinates\n",
        "\n",
        "**Styling**\n",
        "\n",
        "-   node color, shape, size\n",
        "-   edge arrows and weights\n",
        "-   groups / clustering\n",
        "\n",
        "**Large graph support**\n",
        "\n",
        "-   handles **thousands of nodes smoothly**\n",
        "\n",
        "## Import and Setup\n",
        "\n",
        "In PyVis, the core object you use to build, configure, and display\n",
        "interactive graphs is the `Network` object.\n",
        "\n",
        "You create a `Network` to add nodes and edges, customize visualization\n",
        "options, and generate/export an interactive HTML file.\n",
        "\n",
        "``` python\n",
        "from pyvis.network import Network\n",
        "```\n",
        "\n",
        "Optional imports when building graphs:\n",
        "\n",
        "``` python\n",
        "import networkx as nx\n",
        "import pandas as pd\n",
        "```\n",
        "\n",
        "## Adding Nodes manually\n",
        "\n",
        "    net = Network(height=\"600px\", width=\"100%\", bgcolor=\"#222222\", font_color=\"white\")\n",
        "    net.add_node(1, label=\"A\")\n",
        "    net.add_node(2, label=\"B\")\n",
        "    net.add_edge(1, 2)\n",
        "    net.show(\"example.html\")\n",
        "\n",
        "## Python Ecosystem\n",
        "\n",
        "    NetworkX graph\n",
        "          ↓\n",
        "    PyVis conversion\n",
        "          ↓\n",
        "    Vis.js interactive HTML visualization\n",
        "\n",
        "-   Advantages\n",
        "    -   fast WebGL-style rendering\n",
        "    -   extremely interactive\n",
        "    -   simple graph data model\n",
        "    -   works directly in browsers\n",
        "-   Limitations\n",
        "    -   primarily **frontend JavaScript**\n",
        "    -   development of the original library slowed (community forks\n",
        "        exist)\n",
        "\n",
        "## Common PyVis functions\n",
        "\n",
        "-   **Initialize network**\n",
        "    -   Create visualization canvas and global styling\n",
        "-   **Add nodes**\n",
        "    -   Define graph entities with labels, colors, sizes, groups, and\n",
        "        hover text\n",
        "-   **Add edges**\n",
        "    -   Define relationships between nodes with weights, labels, and\n",
        "        styles\n",
        "-   **Import graphs**\n",
        "    -   Convert existing **NetworkX graphs** directly into PyVis\n",
        "        visualizations\n",
        "-   **Configure layout physics**\n",
        "    -   Force-directed layout controlling repulsion, gravity, and spring\n",
        "        forces\n",
        "-   **Customize appearance**\n",
        "    -   Control node size, color, shape, edge thickness, labels, and\n",
        "        clustering\n",
        "-   **Enable interactive controls**\n",
        "    -   Optional UI panel for adjusting physics, layout, and styling in\n",
        "        the browser\n",
        "-   **Adjust interaction behavior**\n",
        "    -   Hover tooltips, node dragging, zooming, and panning\n",
        "-   **Export visualization**\n",
        "    -   Generate a **self-contained interactive HTML network graph**\n",
        "\n",
        "## Demo: PyVis"
      ],
      "id": "86b0306a-24b1-47ef-ad11-13977e4e2183"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "graph.html"
          ]
        },
        {
          "output_type": "display_data",
          "metadata": {},
          "data": {
            "text/html": [
              "\n",
              "        <iframe\n",
              "            width=\"800\"\n",
              "            height=\"600\"\n",
              "            src=\"graph.html\"\n",
              "            frameborder=\"0\"\n",
              "            allowfullscreen\n",
              "            \n",
              "        ></iframe>\n",
              "        "
            ]
          }
        }
      ],
      "source": [
        "import networkx as nx\n",
        "from pyvis.network import Network\n",
        "\n",
        "G = nx.erdos_renyi_graph(50, 0.05)\n",
        "\n",
        "# To fix display issues in Jupyter on Chrome/Safari, use cdn_resources='in_line'\n",
        "net = Network(notebook=True, cdn_resources='in_line')\n",
        "net.from_nx(G)\n",
        "net.show_buttons(filter_=['physics', \"nodes\", \"edges\"])\n",
        "\n",
        "net.show(\"graph.html\")\n",
        "\n",
        "# load as iframe in jupyter notebook\n",
        "from IPython.display import IFrame\n",
        "IFrame(\"graph.html\", width=800, height=600)\n"
      ],
      "id": "6fba0c51"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# NetworkX + Plotly\n",
        "\n",
        "## Steps for Interactive Network Visualization\n",
        "\n",
        "Create an **interactive network visualization** with hover, zoom, and\n",
        "pan using Plotly while using NetworkX for graph structure and layouts.\n",
        "\n",
        "\n",
        "    Graph data\n",
        "    ↓\n",
        "    NetworkX graph\n",
        "    ↓\n",
        "    Compute layout positions\n",
        "    ↓\n",
        "    Extract edge coordinates\n",
        "    ↓\n",
        "    Extract node coordinates\n",
        "    ↓\n",
        "    Create Plotly traces\n",
        "    ↓\n",
        "    Build figure\n",
        "    ↓\n",
        "    Interactive visualization\n",
        "\n",
        "Examples: https://plotly.com/python/network-graphs/\n",
        "\n",
        "## 1. Build or Load the Graph\n",
        "\n",
        "Construct the network structure.\n",
        "\n",
        "\n",
        "    import networkx as nx\n",
        "\n",
        "    G = nx.karate_club_graph()\n",
        "\n",
        "Graph data may come from:\n",
        "\n",
        "-   edge lists  \n",
        "-   adjacency matrices  \n",
        "-   dataframes  \n",
        "-   APIs or databases\n",
        "\n",
        "## 2. Compute Node Positions (Layout)\n",
        "\n",
        "Plotly **does not compute graph layouts**, so node positions must be\n",
        "generated first.\n",
        "\n",
        "    pos = nx.spring_layout(G)\n",
        "\n",
        "Common layout algorithms:\n",
        "\n",
        "| Layout                | Idea                  |\n",
        "|-----------------------|-----------------------|\n",
        "| `spring_layout`       | force-directed layout |\n",
        "| `kamada_kawai_layout` | energy minimization   |\n",
        "| `circular_layout`     | circular geometry     |\n",
        "| `spectral_layout`     | Laplacian embedding   |\n",
        "\n",
        "## 3. Build Edge Coordinates\n",
        "\n",
        "Edges are drawn as line segments.\n",
        "\n",
        "\n",
        "    edge_x = []\n",
        "    edge_y = []\n",
        "\n",
        "    for u, v in G.edges():\n",
        "    x0, y0 = pos[u]\n",
        "    x1, y1 = pos[v]\n",
        "\n",
        "edge_x += \\[x0, x1, None\\] edge_y += \\[y0, y1, None\\]\n",
        "\n",
        "`None` separates edges so they are rendered as independent segments.\n",
        "\n",
        "## 4. Create Edge Trace\n",
        "\n",
        "Plotly trace representing all edges.\n",
        "\n",
        "Edges are typically **non-interactive lines**.\n",
        "\n",
        "\n",
        "    import plotly.graph_objects as go\n",
        "\n",
        "    edge_trace = go.Scatter(\n",
        "    x=edge_x,\n",
        "    y=edge_y,\n",
        "    mode='lines',\n",
        "    line=dict(width=1),\n",
        "    hoverinfo='none'\n",
        "    )\n",
        "\n",
        "## 5. Build Node Coordinates\n",
        "\n",
        "Extract node positions from the layout.\n",
        "\n",
        "\n",
        "    node_x = []\n",
        "    node_y = []\n",
        "\n",
        "    for node in G.nodes():\n",
        "    x, y = pos[node]\n",
        "    node_x.append(x)\n",
        "    node_y.append(y)\n",
        "\n",
        "Optional node attributes include:\n",
        "\n",
        "-   degree  \n",
        "-   centrality  \n",
        "-   community group  \n",
        "-   labels\n",
        "\n",
        "## 6. Create Node Trace\n",
        "\n",
        "Nodes are rendered as markers.\n",
        "\n",
        "\n",
        "    node_trace = go.Scatter(\n",
        "    x=node_x,\n",
        "    y=node_y,\n",
        "    mode='markers',\n",
        "    marker=dict(size=15)\n",
        "    )\n",
        "\n",
        "Common enhancements:\n",
        "\n",
        "-   color nodes by degree  \n",
        "-   add hover text  \n",
        "-   display labels\n",
        "\n",
        "## 7. Combine Traces into Figure\n",
        "\n",
        "\n",
        "    fig = go.Figure(\n",
        "    data=[edge_trace, node_trace]\n",
        "    )\n",
        "\n",
        "## 8. Configure Layout\n",
        "\n",
        "Remove axes and enable interaction.\n",
        "\n",
        "\n",
        "    fig.update_layout(\n",
        "    showlegend=False,\n",
        "    hovermode='closest',\n",
        "    xaxis=dict(visible=False),\n",
        "    yaxis=dict(visible=False)\n",
        "    )\n",
        "\n",
        "## 9. Render Interactive Visualization\n",
        "\n",
        "\n",
        "    fig.show()\n",
        "\n",
        "Plotly automatically enables:\n",
        "\n",
        "-   zoom  \n",
        "-   pan  \n",
        "-   hover tooltips  \n",
        "-   image export\n",
        "\n",
        "## Example: NetworkX + Plotly"
      ],
      "id": "7aaeb526-6801-4fe7-a94e-d3688d3cb366"
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {},
      "outputs": [
        {
          "output_type": "display_data",
          "metadata": {},
          "data": {
            "text/plain": [
              "Unable to display output for mime type(s): application/vnd.plotly.v1+json"
            ]
          }
        }
      ],
      "source": [
        "import networkx as nx\n",
        "import plotly.graph_objects as go\n",
        "\n",
        "# -----------------------------\n",
        "# 1. Build a sample graph\n",
        "# -----------------------------\n",
        "G = nx.Graph()\n",
        "\n",
        "edges = [\n",
        "    (\"A\", \"B\"), (\"A\", \"C\"), (\"A\", \"D\"),\n",
        "    (\"B\", \"C\"), (\"B\", \"E\"),\n",
        "    (\"C\", \"F\"), (\"D\", \"E\"),\n",
        "    (\"E\", \"F\"), (\"E\", \"G\"),\n",
        "    (\"F\", \"H\"), (\"G\", \"H\")\n",
        "]\n",
        "G.add_edges_from(edges)\n",
        "\n",
        "# Example node attribute for coloring / hover\n",
        "for node in G.nodes():\n",
        "    G.nodes[node][\"degree\"] = G.degree[node]\n",
        "\n",
        "# -----------------------------\n",
        "# 2. Compute layout positions\n",
        "# -----------------------------\n",
        "pos = nx.spring_layout(G, seed=42)\n",
        "\n",
        "# -----------------------------\n",
        "# 3. Build edge traces\n",
        "# -----------------------------\n",
        "edge_x = []\n",
        "edge_y = []\n",
        "\n",
        "for u, v in G.edges():\n",
        "    x0, y0 = pos[u]\n",
        "    x1, y1 = pos[v]\n",
        "    edge_x += [x0, x1, None]\n",
        "    edge_y += [y0, y1, None]\n",
        "\n",
        "edge_trace = go.Scatter(\n",
        "    x=edge_x,\n",
        "    y=edge_y,\n",
        "    mode=\"lines\",\n",
        "    hoverinfo=\"none\",\n",
        "    line=dict(width=1)\n",
        ")\n",
        "\n",
        "# -----------------------------\n",
        "# 4. Build node trace\n",
        "# -----------------------------\n",
        "node_x = []\n",
        "node_y = []\n",
        "node_text = []\n",
        "node_color = []\n",
        "\n",
        "for node in G.nodes():\n",
        "    x, y = pos[node]\n",
        "    deg = G.degree[node]\n",
        "    node_x.append(x)\n",
        "    node_y.append(y)\n",
        "    node_text.append(f\"Node: {node}<br>Degree: {deg}\")\n",
        "    node_color.append(deg)\n",
        "\n",
        "node_trace = go.Scatter(\n",
        "    x=node_x,\n",
        "    y=node_y,\n",
        "    mode=\"markers+text\",\n",
        "    text=list(G.nodes()),\n",
        "    textposition=\"top center\",\n",
        "    hoverinfo=\"text\",\n",
        "    hovertext=node_text,\n",
        "    marker=dict(\n",
        "        size=22,\n",
        "        color=node_color,\n",
        "        colorbar=dict(title=\"Degree\"),\n",
        "        line=dict(width=1)\n",
        "    )\n",
        ")\n",
        "\n",
        "# -----------------------------\n",
        "# 5. Create figure\n",
        "# -----------------------------\n",
        "fig = go.Figure(\n",
        "    data=[edge_trace, node_trace],\n",
        "    layout=go.Layout(\n",
        "        title=\"Interactive NetworkX + Plotly Graph\",\n",
        "        showlegend=False,\n",
        "        hovermode=\"closest\",\n",
        "        margin=dict(l=20, r=20, t=50, b=20),\n",
        "        xaxis=dict(showgrid=False, zeroline=False, visible=False),\n",
        "        yaxis=dict(showgrid=False, zeroline=False, visible=False),\n",
        "    )\n",
        ")\n",
        "\n",
        "fig.show()"
      ],
      "id": "f14c94a6"
    }
  ],
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "name": "python3",
      "display_name": "5200",
      "language": "python"
    },
    "language_info": {
      "name": "python",
      "codemirror_mode": {
        "name": "ipython",
        "version": "3"
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.14"
    }
  }
}