Skip to content

T-Flet/altair-nx

Repository files navigation

altair-nx

Documentation Status PyPI Version PyPI Downloads Python Versions License Actions Status

Draw interactive NetworkX graphs with Altair

altair-nx offers a similar draw API to NetworkX but returns Altair Charts instead.

This project started as a fork of nx-altair (inactive since 2020) meant for fixing issues and merging pull requests, but after a full code-base rework (causing backward and forward incompatibility) and the implementation of new features (e.g. curved edges, self loops, and much greater customisation), it became reasonable for it to be its own library.

Installation:

pip install altair-nx

Examples

Every function argument is explained in the documentation (and most IDEs will pull from it on hover or for auto-complete), but the simplest starting point for altair-nx is playing around with the tutorial notebook.

PS: if you draw something cool or which could be a good example of using combinations of the various features, feel free to put it in a notebook and open a pull request with it added to the examples folder (note that GitHub suppresses interactive charts, therefore copy the png renderer bit at the top of current examples).

Simple graph

import networkx as nx
import altair_nx as anx

# Generate a random graph
G = nx.fast_gnp_random_graph(n = 20, p = 0.25)

# Compute node positions
pos = nx.spring_layout(G)

# Draw the graph with altair-nx
viz = anx.draw_networkx(G, pos)

# Display it and make it interactive
viz.interactive()

Minimal customisation

Many of altair-nx's style configuration arguments (most being similar to NetworkX's) support declarative mapping to node and edge attributes (e.g. colours, shapes, and sizes). Again, see the documentation or the tutorial notebook, but here is a simple styling of the graph from above:

import numpy as np

# Add attributes to nodes and edges
for n in G.nodes(): G.nodes[n]['importance'] = np.random.randn()
for e in G.edges(): G.edges[e]['weight'] = np.random.uniform(1, 10)

# Draw the graph with altair-nx
viz = anx.draw_networkx(G, pos,
    node_colour = 'importance', node_cmap = 'viridis',
    edge_colour = 'black', edge_width = 'weight', curved_edges = True
)

# Display it and make it interactive
viz.interactive()

Leverage Altair for deeper interactivity

Make a chart depend on a selection over the graph:

interactivity.mp4

Create controls to affect chart parameters:

toggles.mp4

Both examples are in the tutorial notebook.