NetworkX#

NetworkX is a CPU graph manipulation library with a variety of algorithms and layouts. This notebook shows two PyGraphistry workflows: converting a NetworkX graph into a PyGraphistry graph, and enriching a PyGraphistry graph with the public compute_networkx() API.

Install the optional dependency with pip install "pygraphistry[networkx]". Use pygraphistry[networkx-scipy] when you want NetworkX algorithms to use SciPy-backed implementations where NetworkX supports them.

[ ]:
import graphistry
import networkx as nx
import pandas as pd

# To specify a Graphistry account & server for plotting, use:
# graphistry.register(api=3, username="...", password="...", protocol="https", server="hub.graphistry.com")
# For more options: https://pygraphistry.readthedocs.io/en/latest/server/register.html

Convert a NetworkX graph#

from_networkx() preserves node and edge attributes as pandas dataframes. You can inspect or transform the data locally, then call g.plot() after registering with a Graphistry server.

[ ]:
G = nx.Graph()
G.add_nodes_from([
    (1, {"label": "one"}),
    (2, {"label": "two"}),
    (3, {"label": "three"}),
    (4, {"label": "four"}),
    (7, {"label": "seven"}),
    (8, {"label": "eight"}),
])
G.add_edges_from([
    (2, 3, {"kind": "path"}),
    (3, 4, {"kind": "path"}),
    (7, 8, {"kind": "pair"}),
])

g = graphistry.bind(source="src", destination="dst", node="nodeid").from_networkx(G)

assert isinstance(g._edges, pd.DataFrame)
assert isinstance(g._nodes, pd.DataFrame)

g._edges

Enrich nodes with NetworkX algorithms#

compute_networkx() runs the same curated NetworkX algorithm subset exposed by GFQL local Cypher CALL graphistry.nx.*. Node algorithms append columns to g._nodes and preserve the graph bindings.

[ ]:
g_ranked = g.compute_networkx("degree_centrality", out_col="degree_score", directed=False)

assert "degree_score" in g_ranked._nodes.columns
g_ranked._nodes.sort_values("degree_score", ascending=False)

Enrich edges or return a projected graph#

Edge algorithms append columns to g._edges. Graph-returning algorithms such as k_core return a new PyGraphistry graph containing the projected NetworkX graph.

[ ]:
g_edges = g.compute_networkx("edge_betweenness_centrality", out_col="edge_bc", directed=False)
assert "edge_bc" in g_edges._edges.columns

g_core = g.compute_networkx("k_core", params={"k": 1}, directed=False)
assert set(g_core._nodes["nodeid"]) == {2, 3, 4, 7, 8}

g_core._edges

Visualize the enriched graph#

After registering with a Graphistry server, plot() uploads and embeds the interactive graph. This preview colors nodes with a continuous blue-to-red palette from low to high degree_score, making the NetworkX result visible in the rendered docs.

[5]:
degree_palette = ["#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c"]
g_colored = g_ranked.encode_point_color("degree_score", palette=degree_palette, as_continuous=True)
g_colored.plot(render="ipython")
[5]: