API Reference#

This page provides detailed documentation for the lightgraph API.

Visualization#

lightgraph.net_vis(adj_matrix=None, node_names=None, node_groups: Dict[str, str] | str | None = None, group_colors: Dict[str, str] | None = None, group_order: List[str] | None = None, node_colors: Dict[str, str] | None = None, node_sizes: Dict[str, float] | None = None, remove_unconnected: bool = True, edges=None, nodes=None, node_metric: Dict[str, float] | None = None, metric_map: Literal['size', 'color', 'both'] = 'size', metric_size_range: tuple = (4, 20), metric_colors: tuple = ('#c6dbef', '#08306b'), metric_label: str | None = None, show_arrows: bool = False, show_labels: bool = True, show_ellipses: bool = True, show_legend: bool = True, show_statistics: bool = False, show_tooltips: bool = True, highlight_neighbors: bool = True, neighbor_fade: float = 0.15, ego_filter: bool = True, ego_depth: int = 1, layout: Literal['force', 'circular'] = 'force', simulation_strength: float = 4000, link_distance: float = 100, group_attraction: float = 0.3, warmup_ticks: str | int = 'auto', node_size: float = 7, node_color: str | None = None, label_font_size: float = 5, edge_width: float | None = None, edge_color: str | None = None, edge_opacity: float | None = None, edge_weight_to_width: bool = False, edge_weight_to_opacity: bool = False, weight_width_range: tuple = (0.5, 4), weight_opacity_range: tuple = (0.05, 0.6), theme: Literal['light', 'dark'] = 'light', background_color: str | None = None, auto_fit: bool = True, zoom_range: tuple = (0.1, 5), pixel_ratio: float | None = None, export_scale: float = 2, config: dict | None = None, height: str = '800px', save_as: str | None = None) NetworkVisualization[source]#

Visualizes a network using lightGraph in Jupyter.

Accepts either an adjacency matrix (dense numpy or scipy.sparse) with node_names, or an edge list via the edges keyword. For large graphs an edge list or sparse matrix is strongly preferred: a dense 10,000-node matrix holds 100M entries to describe what is usually a few thousand edges.

Parameters:
  • adj_matrix (np.ndarray or scipy.sparse matrix, optional) – The adjacency matrix of the network (n x n). Symmetric matrices are treated as undirected and each edge is emitted once (unless show_arrows=True, where both directions are kept).

  • node_names (array-like, optional) – Node names corresponding to rows/columns of the matrix. Required with adj_matrix; optional with edges (derived from the edge list).

  • edges (list or pandas.DataFrame, optional) – Edge list alternative to adj_matrix. Accepts (source, target) or (source, target, weight) tuples, dicts with source/target/weight keys, or a DataFrame with source/target[/weight] columns.

  • nodes (list or pandas.DataFrame, optional) – Optional node table: dicts (or DataFrame rows) with an ‘id’ key and optional ‘group’, ‘color’, ‘size’ attributes. Provides node order and per-node styling in one place; the explicit node_groups / node_colors / node_sizes dicts win over table columns.

  • node_metric (dict, optional) – Mapping of node name to a numeric value (degree, PageRank, any score — see lightgraph.analytics). Values are min-max normalized and mapped to node size and/or color per metric_map. Explicit node_sizes/node_colors entries win over metric-derived ones; group colors always win over node colors.

  • metric_map ({'size', 'color', 'both'}, default 'size') – Which visual channel(s) node_metric drives.

  • metric_size_range (tuple, default (4, 20)) – Node size range (min, max) for metric-driven sizing.

  • metric_colors (tuple, default ('#c6dbef', '#08306b')) – Low/high hex colors for metric-driven coloring.

  • metric_label (str, optional) – Title for the metric section of the legend (e.g. ‘PageRank’). Defaults to ‘Metric’. The legend section appears whenever node_metric drives size and/or color and show_legend is on.

  • node_groups (dict or 'auto', optional) – Dictionary mapping node names to group identifiers for coloring. Pass ‘auto’ to detect communities automatically (networkx Louvain when installed, else a built-in label-propagation fallback).

  • group_colors (dict, optional) – Mapping of group name to hex color (e.g. {‘alpha’: ‘#ff7f0e’}), pinning those groups’ colors. Unpinned groups stay on the default palette. Names matching no group are ignored, so one mapping can be reused across filtered subsets of the same data.

  • group_order (list, optional) – Explicit group ordering for palette assignment. Groups keep their palette slot even when absent from the data, so passing the same list (e.g. computed once from the full dataset) to every figure in a series keeps each group’s color stable across subsets. Groups not listed are appended in sorted order. Without group_order, groups are assigned palette colors in sorted-name order.

  • node_colors (dict, optional) – Dictionary mapping node names to hex color strings (e.g., ‘#FF5733’).

  • node_sizes (dict, optional) – Dictionary mapping node names to size values.

  • remove_unconnected (bool, default True) – Whether to remove nodes with no connections.

  • show_arrows (bool, default False) – Whether to show directional arrows on edges.

  • show_labels (bool, default True) – Whether to show node labels.

  • show_ellipses (bool, default True) – Whether to show group ellipses around clustered nodes.

  • show_legend (bool, default True) – Whether to show the group legend.

  • show_statistics (bool, default False) – Whether to show the statistics panel.

  • show_tooltips (bool, default True) – Whether to show tooltips on hover.

  • highlight_neighbors (bool, default True) – Fade everything outside the 1-hop neighborhood of hovered or selected nodes.

  • neighbor_fade (float, default 0.15) – Opacity multiplier applied to faded elements while highlighting.

  • ego_filter (bool, default True) – Double-clicking a node shows only its k-hop neighborhood (double-click empty space or press Escape to restore).

  • ego_depth (int, default 1) – Neighborhood depth (hops) for the ego filter.

  • layout ({'force', 'circular'}, default 'force') – Layout algorithm to use. - ‘force’: Force-directed layout using physics simulation. - ‘circular’: Nodes arranged in a circle, grouped by category.

  • simulation_strength (float, default 4000) – Repulsion strength for force-directed layout (divided by node count).

  • link_distance (float, default 100) – Target distance between connected nodes.

  • group_attraction (float, default 0.3) – Strength of the pull toward each group’s centroid in the force layout, which separates groups spatially. 0 disables.

  • warmup_ticks ('auto' or int, default 'auto') – Synchronous layout ticks run before the first paint so the graph appears already untangled. ‘auto’ spends a roughly fixed time budget; a number forces that tick count; 0 disables.

  • node_size (float, default 7) – Default size for nodes.

  • node_color (str, optional) – Default node fill color (hex). Defaults to the theme color.

  • label_font_size (float, default 5) – Font size for node labels.

  • edge_width (float, optional) – Base width for edges (JS default 0.45).

  • edge_color (str, optional) – Default edge color (hex). Defaults to the theme color.

  • edge_opacity (float, optional) – Opacity for edges (0.0 to 1.0). By default opacity adapts automatically to the on-screen edge density and zoom level, so dense graphs stay readable; setting a value pins it (users can still re-enable auto mode from the settings sidebar).

  • edge_weight_to_width (bool, default False) – Scale edge width by edge weight.

  • edge_weight_to_opacity (bool, default False) – Scale edge opacity by edge weight.

  • weight_width_range (tuple, default (0.5, 4)) – Edge width range (min, max) used by edge_weight_to_width.

  • weight_opacity_range (tuple, default (0.05, 0.6)) – Edge opacity range (min, max) used by edge_weight_to_opacity.

  • theme ({'light', 'dark'}, default 'light') – UI and canvas color theme.

  • background_color (str, optional) – Background color for the canvas (hex color). Defaults to white in the light theme and near-black in the dark theme.

  • auto_fit (bool, default True) – Zoom to fit the graph once the layout settles (skipped if the user already panned/zoomed manually).

  • zoom_range (tuple, default (0.1, 5)) – Minimum and maximum zoom factors.

  • pixel_ratio (float, optional) – Backing-store resolution multiplier. Defaults to the display’s devicePixelRatio (sharp on retina); set 1 to trade sharpness for speed on very large graphs.

  • export_scale (float, default 2) – Resolution multiplier for PNG export, relative to on-screen size.

  • config (dict, optional) – Raw lightGraph config (JS shape, e.g. {‘nodes’: {‘borderWidth’: 2}}) deep-merged over everything above — full access to any JS option without a dedicated keyword.

  • height (str, default '800px') – Height of the visualization container.

  • save_as (str, optional) – If provided, save the HTML to this file path.

Returns:

Object that auto-displays in Jupyter notebooks. Access raw HTML via str() or .html property.

Return type:

NetworkVisualization

Examples

>>> import numpy as np
>>> from lightgraph import net_vis
>>> adj = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
>>> names = np.array(['A', 'B', 'C'])
>>> groups = {'A': 'group1', 'B': 'group2', 'C': 'group1'}
>>> html = net_vis(adj, names, node_groups=groups)

Using an edge list plus the analytics helpers:

>>> from lightgraph import net_vis, pagerank, communities
>>> edges = [('A', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'D')]
>>> html = net_vis(edges=edges, node_metric=pagerank(edges),
...                node_groups=communities(edges))
class lightgraph.NetworkVisualization(html_content: str, height: str = '800px')[source]#

Wrapper for lightGraph network visualization HTML content.

Implements Jupyter’s rich display protocol via _repr_html_(). Uses iframe isolation so multiple visualizations can coexist in a single notebook without element ID collisions.

__init__(html_content: str, height: str = '800px')[source]#
property html: str#

The raw HTML content as a string.

__str__() str[source]#

Returns raw HTML for backward compatibility.

__contains__(item: str) bool[source]#

Support ‘in’ operator for backward compatibility.

save(filepath: str) None[source]#

Save the visualization as a standalone HTML file.

Analytics#

Dependency-free graph analytics. Every function accepts the same flexible edge input as net_vis (tuples, dicts, or a pandas DataFrame) and returns plain dicts keyed by node name, ready to pass back to net_vis(node_metric=..., node_groups=...).

Dependency-free graph analytics for lightgraph.

Every function accepts the same flexible edge input as net_vis(): a list of (source, target) / (source, target, weight) tuples, a list of dicts with source/target/weight keys, or a pandas DataFrame with source/target (and optional weight) columns.

Results are plain dicts keyed by node name, designed to plug straight back into the visualization:

from lightgraph import net_vis, pagerank, communities

net_vis(edges=edges,
        node_metric=pagerank(edges),
        node_groups=communities(edges))

Graphs are treated as undirected and self-loops are ignored; parallel edges have their weights summed. Nodes are discovered from the edge list, so isolated nodes do not appear in the results.

When networkx is installed, communities() uses its Louvain implementation; everything else is pure Python (Brandes betweenness, BFS closeness, power-iteration PageRank/eigenvector), which is fast enough for the tens of thousands of edges lightgraph is built to draw.

lightgraph.analytics.degree(edges, weighted=False)[source]#

Degree (neighbor count) or, with weighted=True, strength (sum of incident edge weights) of every node. Returns {node: value}.

lightgraph.analytics.betweenness(edges, normalized=True)[source]#

Shortest-path betweenness centrality (Brandes’ algorithm, edges treated as unweighted). With normalized=True values are divided by the number of node pairs, so they are comparable across graph sizes. Returns {node: value}.

lightgraph.analytics.closeness(edges)[source]#

Closeness centrality (edges treated as unweighted), using the Wasserman-Faust correction so scores stay comparable when the graph has several connected components. Returns {node: value}.

lightgraph.analytics.eigenvector(edges, weighted=True, max_iter=200, tol=1e-08)[source]#

Eigenvector centrality via power iteration on the (weighted) adjacency matrix. Returns {node: value} normalized to unit length.

lightgraph.analytics.pagerank(edges, damping=0.85, weighted=True, max_iter=200, tol=1e-10)[source]#

PageRank on the undirected (weighted) graph. Returns {node: value} summing to 1.

lightgraph.analytics.communities(edges, seed=42)[source]#

Community detection: networkx Louvain when installed, else a built-in label-propagation fallback. Returns {node: ‘c1’, …} with communities numbered largest-first; singleton communities and isolated nodes are left out, so the result can be passed directly to net_vis(node_groups=…).

lightgraph.analytics.components(edges)[source]#

Connected components. Returns {node: component_id} with integer ids numbered from 1 in decreasing component size.

lightgraph.analytics.neighbors(edges, node, depth=1)[source]#

The k-hop neighborhood of a node (the same set the interactive double-click ego filter shows). Returns a sorted list of node names including the node itself.

lightgraph.analytics.summary(edges)[source]#

Headline statistics of the graph. Returns a dict with node/edge counts, density, degree stats, component structure, and the global clustering coefficient (transitivity).

lightgraph.analytics.top_nodes(metric, n=10)[source]#

The n highest-scoring entries of a metric dict, as a list of (node, value) tuples sorted by decreasing value.

Datasets#

Small bundled example networks.

Each loader returns plain lists of dicts that can be passed directly to lightgraph.net_vis() and the lightgraph.analytics functions (no pandas required; pd.DataFrame(edges) converts them if you want a table).

All three are classic, freely redistributed research datasets; please cite the source papers noted in each docstring if you use them in published work.

lightgraph.datasets.les_mis()[source]#

Character co-occurrence network of Les Misérables.

77 characters, 254 weighted edges; the weight counts the chapters in which two characters appear together.

Source: D. E. Knuth, The Stanford GraphBase: A Platform for Combinatorial Computing (1993).

Returns:

list of dicts with keys source, target, weight.

Example

>>> from lightgraph import net_vis, datasets
>>> net_vis(edges=datasets.les_mis(), edge_weight_to_width=True)
lightgraph.datasets.got()[source]#

Character interaction network of A Storm of Swords.

107 characters, 352 weighted edges; the weight counts interactions (co-mentions within 15 words) in the third book of A Song of Ice and Fire.

Source: A. Beveridge and J. Shan, “Network of Thrones”, Math Horizons 23(4), 18-22 (2016).

Returns:

list of dicts with keys source, target, weight.

Example

>>> from lightgraph import net_vis, datasets, communities
>>> edges = datasets.got()
>>> net_vis(edges=edges, node_groups=communities(edges))
lightgraph.datasets.football()[source]#

American college football games of the Fall 2000 season.

115 Division IA teams, 613 games. Each node carries its conference as group, giving a ground-truth community structure.

Source: M. Girvan and M. E. J. Newman, “Community structure in social and biological networks”, PNAS 99, 7821-7826 (2002).

Returns:

nodes is a list of dicts with keys id and group; edges a list of dicts with keys source and target.

Return type:

(nodes, edges) tuple

Example

>>> from lightgraph import net_vis, datasets
>>> nodes, edges = datasets.football()
>>> net_vis(edges=edges, nodes=nodes)

R Interface#

The R package mirrors the Python interface one-to-one. lightgraph(nodes, edges, ...) accepts the same arguments as net_vis (in snake_case, as in Python), and the analytics functions carry an lg_ prefix:

R function

Python equivalent

lightgraph()

net_vis()

lg_degree()

lightgraph.degree()

lg_betweenness()

lightgraph.betweenness()

lg_closeness()

lightgraph.closeness()

lg_eigenvector()

lightgraph.eigenvector()

lg_pagerank()

lightgraph.pagerank()

lg_communities()

lightgraph.communities()

lg_components()

lightgraph.components()

lg_neighbors()

lightgraph.neighbors()

lg_summary()

lightgraph.summary()

lg_top_nodes()

lightgraph.top_nodes()

data(les_mis)

lightgraph.datasets.les_mis()

data(got)

lightgraph.datasets.got()

data(football_edges), data(football_nodes)

lightgraph.datasets.football()

lightgraphOutput()

(Shiny output binding)

renderLightgraph()

(Shiny render function)

adjacency_to_lightgraph()

(adjacency matrices go straight to net_vis in Python)

R functions return named vectors instead of dicts; see ?lg_pagerank etc. in R for the full manual pages, and the R vignette for a worked example.

JavaScript API#

Both bindings drive the same lightgraph.js runtime. The config argument (Python dict / R named list) is deep-merged over the generated configuration, giving access to every option in the JS DEFAULT_CONFIG (nodes, edges, highlight, egoFilter, labels, simulation, groups, canvas, ui, layout) without a dedicated keyword argument.