{ "cells": [ { "cell_type": "markdown", "id": "29b63028-e476-4840-bfa8-933ab4a392a8", "metadata": { "tags": [] }, "source": [ "# NetworkX and PyVis" ] }, { "cell_type": "markdown", "id": "9d888a94-ea5c-443d-8aa3-a69bfe1063a7", "metadata": {}, "source": [ "While this works, we don't have all the advantages that NetworkX afforded us. PyVis, it is important to note, while useful, is primarily a wrapper for producing JavaScript graphs. It is not as robust as NetworkX when it comes to handling and querying complex network relationships. We cannot generate, for example, metrics for things like centrality. For these reasons, it is best to combine the best of NetworkX and PyVis by first passing your network data to NetworkX, creating the graph, and then passing the NetworkX graph to PyVis for conversion to an interactive graph.\n", "\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "bdd0cd67-4b47-4bb0-ac64-f2cc88f73572", "metadata": {}, "outputs": [], "source": [ "import networkx as nx" ] }, { "cell_type": "markdown", "id": "a4f84256-4c9b-4e81-84e3-6e3552d53bb8", "metadata": {}, "source": [ "Just as we did in the previous section, we will create a NetworkX `nx.Graph()` and populate it with our relationships." ] }, { "cell_type": "code", "execution_count": 7, "id": "c04c2fe5-ec4f-40a7-8879-3d4dee925693", "metadata": {}, "outputs": [], "source": [ "G = nx.Graph()\n", "rels = [\n", " \n", " [\"Fred\", \"George\"],\n", " [\"Harry\", \"Rita\"],\n", " [\"Fred\", \"Ginny\"],\n", " [\"Tom\", \"Ginny\"],\n", " [\"Harry\", \"Ginny\"],\n", " [\"Harry\", \"George\"],\n", " [\"Frank\", \"Ginny\"],\n", " [\"Marge\", \"Rita\"],\n", " [\"Fred\", \"Rita\"]\n", " \n", "]\n", "G.add_edges_from(rels)" ] }, { "cell_type": "markdown", "id": "37f4b419-f9f8-46b0-be87-792ab5d38b4c", "metadata": {}, "source": [ "Now that we have our NetworkX Graph, we can create a PyVis `Network` class." ] }, { "cell_type": "code", "execution_count": 8, "id": "8ba45046-7414-4635-98a0-57bfe14ff1f4", "metadata": {}, "outputs": [], "source": [ "net = Network()" ] }, { "cell_type": "markdown", "id": "3ca89fa1-e930-4eda-ad18-50045725e8e8", "metadata": {}, "source": [ "Using the `from_nx()` method, which will take a single argument, our NetworkX `Graph`, or `G`." ] }, { "cell_type": "code", "execution_count": 9, "id": "226dfcc0-e9e2-4504-8a4c-4c095e3a4669", "metadata": {}, "outputs": [], "source": [ "net.from_nx(G)" ] }, { "cell_type": "markdown", "id": "89233d79-8b74-41ae-851f-30450f0a0c6c", "metadata": {}, "source": [ "With the data now populated, we can save and view our PyVis `Network`." ] }, { "cell_type": "code", "execution_count": 10, "id": "be2d18b7-1a03-43e3-9380-4d6fc6e009e0", "metadata": {}, "outputs": [], "source": [ "net.save_graph(\"networkx-pyvis.html\")" ] }, { "cell_type": "code", "execution_count": 11, "id": "5a20b5a0-fada-4627-bc03-f49b15908053", "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "