Skip to content

plot

Plotly figures for any NetworkX graph, flow table, or mapping from period to graph. Every function returns a plotly.graph_objects.Figure and never calls show(). Call fig.show(), fig.write_html(...) or fig.write_image(...) yourself (static image export needs Kaleido, which is not a dependency).

Every function uses the same argument names for the same things; the Concepts page lists them and says which chart uses which. All functions below are available as nv.plot.<name>.

Choosing a chart

auto

auto(
    data: Any,
    kind: Kind | Literal["map"] = "auto",
    **kwargs: Any,
) -> Figure

Draw a chart by name, or let the data choose one.

auto(g, kind="sankey", top_n=8) is the same as plot.sankey(g, top_n=8). With kind="auto" the chart is chosen by the rules in choose_kind, and the choice is recorded in the figure: fig.layout.meta["netviz"] holds {"kind": ..., "reason": ...} and a line under the title names the chart and the reason.

Every chart function uses the same argument names (color_by, size_by, edge_width_by, edge_color_by, label_by, show_labels, top_n, focus, time, category, labels, title, height), so the same keyword arguments work whichever chart is drawn, as long as that chart uses them.

Parameters:

Name Type Description Default
data Any

A NetworkX graph, a flow table, a mapping from period to graph, a period-indexed table, or a power-law fit.

required
kind Kind | Literal['map']

A chart name (see Kind) or "auto".

'auto'
**kwargs Any

Passed to the chart function.

{}

Returns:

Type Description
Figure

The figure. It is not shown.

Raises:

Type Description
ValueError

For an unknown kind.

TypeError

If a keyword argument is not used by the chosen chart. The message names the chart, why it was chosen, and the arguments it accepts.

Examples:

>>> import networkx as nx
>>> import netviz_tools as nv
>>> fig = nv.plot.auto(nx.karate_club_graph())
>>> fig.layout.meta["netviz"]["kind"]
'network'

choose_kind

choose_kind(data: object, **kwargs: Any) -> tuple[str, str]

Return the chart auto would draw, and the reason, without drawing it.

The rules are checked in this order:

==================================================== ====================== condition chart ==================================================== ====================== data is a power-law fit degree_distribution data is a table indexed by period (not flows) time_series one focus node, flows with several categories compare one focus node, several periods time_series one focus node ego every node has coordinates flow_map directed, and no node both sends and receives sankey anything else network ==================================================== ======================

flow_map and network are animated over time when the data span several periods. Nodes have coordinates when they carry lon/lat attributes, when coords= is given, or when they are FAOSTAT country names.

Parameters:

Name Type Description Default
data object

What would be passed to auto.

required
**kwargs Any

The keyword arguments that would be passed (focus, time, category, labels, node_attrs, coords are used).

{}

Returns:

Type Description
tuple of str

(kind, reason).

Kind module-attribute

Kind: TypeAlias = Literal[
    "auto",
    "network",
    "flow_map",
    "sankey",
    "adjacency",
    "ego",
    "ranking",
    "compare",
    "time_series",
    "degree_distribution",
]

Chart names accepted by auto. "map" is accepted as an alias of "flow_map".

KINDS module-attribute

KINDS: Final[Mapping[str, Callable[..., Figure]]] = {
    "network": network,
    "flow_map": flow_map,
    "map": flow_map,
    "sankey": sankey,
    "adjacency": adjacency,
    "ego": ego,
    "ranking": ranking,
    "compare": compare,
    "time_series": time_series,
    "degree_distribution": degree_distribution,
}

Every chart function reachable through auto, by name.

network

network(
    data: PlotData,
    *,
    layout: Layout = "spring",
    color_by: NodeSpec = "auto",
    size_by: NodeSpec = "auto",
    edge_width_by: EdgeSpec = "auto",
    edge_color_by: EdgeSpec = None,
    label_by: str | None = None,
    show_labels: ShowLabels = "auto",
    top_n: int | None = None,
    focus: Hashable | Iterable[Hashable] | None = None,
    time: Selector = None,
    category: Selector = None,
    labels: Mapping[str, str] | None = None,
    title: str | None = None,
    height: int = 650,
    pos: Mapping[Any, tuple[float, float]] | None = None,
    partition: Series | None = None,
    seed: int = 42,
    min_weight_quantile: float | None = None,
    max_nodes: int | None = 2000,
    layout_options: Mapping[str, Any] | None = None,
    node_attrs: DataFrame | None = None,
) -> Figure

Draw any NetworkX graph as an interactive node-link diagram.

Works on networkx.Graph, DiGraph and the multigraph classes (parallel edges are summed). Directed edges get an arrowhead pointing at the target. Hover over a node for its attributes and the values behind its colour and size; hover over an arrowhead or edge midpoint for the edge.

With several periods (a flow table spanning several times, or a mapping of graphs) the figure is animated: one frame per period, with a play button and a time slider. Node positions stay fixed across frames.

Parameters:

Name Type Description Default
data PlotData

A NetworkX graph, a flow table, or a mapping from period to graph (for example nv.graphs_by(flows, by="time")).

required
layout Layout

Node placement, see Layout. Ignored when pos is given.

'spring'
color_by NodeSpec

Node colour: a node attribute name, a metric name (NodeMetric), a mapping or Series from node to value, None, or "auto" (communities when the graph has edges). Text and other non-numeric values get a legend with up to eight colours; numbers get a colour bar.

'auto'
size_by NodeSpec

Node size, same forms as color_by. "auto" is "strength" (weighted degree) when edges have a weight attribute, otherwise "degree". Sizes are log-scaled when values span more than two orders of magnitude.

'auto'
edge_width_by EdgeSpec

Edge attribute (or mapping from (u, v)) for edge width. "auto" uses "weight" when present, otherwise equal widths.

'auto'
edge_color_by EdgeSpec

Edge attribute or mapping for edge colour, or "source" / "target" to colour each edge like that end node. None (default) draws edges grey.

None
label_by str | None

Node attribute to use as label text. Defaults to the node itself.

None
show_labels ShowLabels

Which nodes get a text label, see ShowLabels.

'auto'
top_n int | None

Keep the top_n largest nodes by size_by (by degree when size_by is not numeric). None keeps all, up to max_nodes.

None
focus Hashable | Iterable[Hashable] | None

Node or nodes to emphasise: always drawn and labelled, outlined, with their edges darker while other nodes fade.

None
time Selector

With a flow table or mapping of graphs: one period, or several to animate over. None uses every period.

None
category Selector

With a flow table: the category to draw (required when the table holds more than one).

None
labels Mapping[str, str] | None

Display labels for hover text, legends and captions, for example {"source": "Exporter", "weight": "Tonnes"}. Merged over labels carried by the data.

None
title str | None

Figure title. Defaults to one built from the graph's category, time or name.

None
height int

Figure height in pixels.

650
pos Mapping[Any, tuple[float, float]] | None

Your own node positions, {node: (x, y)}; overrides layout.

None
partition Series | None

Community id per node, used by color_by="community" and layout="community". Computed with Louvain (seed 0) when omitted.

None
seed int

Seed for the layout, so the same call draws the same picture.

42
min_weight_quantile float | None

Hide edges whose edge_width_by value is below this quantile (between 0 and 1) to reduce clutter.

None
max_nodes int | None

Safety cap when top_n is None: larger graphs are cut to the max_nodes largest nodes with a warning. None disables it.

2000
layout_options Mapping[str, Any] | None

Extra keyword arguments for the NetworkX layout function.

None
node_attrs DataFrame | None

With a flow table: a table indexed by node whose columns become node attributes (for example faostat.countries()).

None

Returns:

Type Description
Figure

The figure. It is not shown; call fig.show() yourself.

Raises:

Type Description
UnknownMetricError

If color_by or size_by is neither a node attribute nor a metric.

ValueError

For an unknown layout or focus node, or pos missing nodes.

Examples:

>>> import networkx as nx
>>> import netviz_tools as nv
>>> fig = nv.plot.network(nx.karate_club_graph(), color_by="club")
>>> [t.name for t in fig.data if t.showlegend]
['Mr. Hi', 'Officer']

ego

ego(
    data: PlotData,
    focus: Hashable | Iterable[Hashable],
    *,
    radius: int = 1,
    undirected: bool = True,
    layout: Layout = "spring",
    color_by: NodeSpec = "auto",
    size_by: NodeSpec = "auto",
    edge_width_by: EdgeSpec = "auto",
    edge_color_by: EdgeSpec = None,
    label_by: str | None = None,
    show_labels: ShowLabels = True,
    top_n: int | None = None,
    time: Selector = None,
    category: Selector = None,
    labels: Mapping[str, str] | None = None,
    title: str | None = None,
    height: int = 600,
    seed: int = 42,
    node_attrs: DataFrame | None = None,
) -> Figure

Draw the neighbourhood of one or more nodes.

Keeps the focus node(s) and every node within radius steps, then draws them like network with the focus emphasised.

Parameters:

Name Type Description Default
data PlotData

A NetworkX graph, a flow table, or a mapping from period to graph.

required
focus Hashable | Iterable[Hashable]

The centre node, or several centres (their neighbourhoods are joined).

required
radius int

Number of steps from the centre to include.

1
undirected bool

Follow edges in both directions on a directed graph (default). If False, only successors are included.

True
layout Layout

As in network. Every node is labelled by default.

'spring'
color_by Layout

As in network. Every node is labelled by default.

'spring'
size_by Layout

As in network. Every node is labelled by default.

'spring'
edge_width_by Layout

As in network. Every node is labelled by default.

'spring'
edge_color_by Layout

As in network. Every node is labelled by default.

'spring'
label_by Layout

As in network. Every node is labelled by default.

'spring'
show_labels Layout

As in network. Every node is labelled by default.

'spring'
top_n int | None

Keep only the top_n largest neighbours (the centre always stays).

None
time Selector

As in network.

None
category Selector

As in network.

None
labels Selector

As in network.

None
title Selector

As in network.

None
height Selector

As in network.

None
seed Selector

As in network.

None
node_attrs Selector

As in network.

None

Returns:

Type Description
Figure

The figure. It is not shown.

flow_map

flow_map(
    data: PlotData,
    *,
    color_by: NodeSpec = "auto",
    size_by: NodeSpec = "auto",
    edge_width_by: EdgeSpec = "auto",
    edge_color_by: EdgeSpec = None,
    label_by: str | None = None,
    show_labels: ShowLabels = False,
    top_n: int = 60,
    focus: Hashable | Iterable[Hashable] | None = None,
    time: Selector = None,
    category: Selector = None,
    labels: Mapping[str, str] | None = None,
    title: str | None = None,
    height: int = 550,
    coords: DataFrame | None = None,
    projection: str = "natural earth",
    seed: int = 42,
    node_attrs: DataFrame | None = None,
) -> Figure

Draw the largest flows on a world map, animated over time when there are several periods.

Edges are drawn as great-circle lines between node coordinates. With a flow table spanning several periods (or a mapping of graphs), each period becomes an animation frame with a play button and a time slider, so you can watch flows between places change year by year: trade, migration, shipping, or anything else with an origin and a destination.

Parameters:

Name Type Description Default
data PlotData

A NetworkX graph, a flow table, or a mapping from period to graph.

required
color_by NodeSpec

As in network.

'auto'
size_by NodeSpec

As in network.

'auto'
edge_width_by NodeSpec

As in network.

'auto'
edge_color_by NodeSpec

As in network.

'auto'
label_by NodeSpec

As in network.

'auto'
show_labels ShowLabels

Which nodes get a text label (none by default; hover shows names).

False
top_n int

Number of largest edges (by edge_width_by) to draw in each period.

60
focus Hashable | Iterable[Hashable] | None

Node or nodes to follow: only flows touching them are drawn (the top_n largest), and they are outlined and labelled.

None
time Selector

As in network.

None
category Selector

As in network.

None
labels Selector

As in network.

None
title Selector

As in network.

None
height Selector

As in network.

None
seed Selector

As in network.

None
node_attrs Selector

As in network.

None
coords DataFrame | None

Table indexed by node with lon and lat columns. Defaults to node attributes lon/lat when every node has them, otherwise to the FAOSTAT country label points bundled with the package (derived from Natural Earth).

None
projection str

Any Plotly geo projection type, for example "natural earth" or "equirectangular".

'natural earth'

Returns:

Type Description
Figure

The figure. It is not shown.

Warns:

Type Description
UserWarning

If some endpoints of the selected edges have no coordinates. Those edges are skipped.

Layout module-attribute

Layout: TypeAlias = Literal[
    "spring",
    "kamada_kawai",
    "circular",
    "shell",
    "spectral",
    "community",
    "bipartite",
    "multipartite",
    "geo",
]

Node placement for network.

  • "spring": Fruchterman-Reingold force layout, seeded (default). Above 500 nodes it runs fewer iterations (20 at 1,250 nodes and more) to stay fast; pass layout_options={"iterations": 50} for the full run.
  • "kamada_kawai": path-length preserving layout; slow above about 500 nodes.
  • "circular": nodes on a circle, largest first.
  • "shell": concentric circles, one per colour category when color_by is categorical.
  • "spectral": eigenvectors of the graph Laplacian; fast on large graphs. Like "kamada_kawai", it lays out each connected component separately and packs them side by side.
  • "community": each community in its own cluster (see community_layout).
  • "bipartite": two columns, from the bipartite node attribute (0/1) or a two-colouring of the graph.
  • "multipartite": one column per value of the subset node attribute (change it with layout_options={"subset_key": "layer"}).
  • "geo": nodes at their lon/lat attributes on a world map.

community_layout

community_layout(
    g: Graph[Any],
    partition: Series,
    *,
    seed: int = 42,
    spread: float = 4.0,
) -> dict[Hashable, tuple[float, float]]

Place each community in its own cluster.

Community centres sit on a circle, then each community is laid out around its centre (Kamada-Kawai when it is connected and has at most 150 nodes, otherwise a spring layout) with a radius that grows with the square root of its size. The circle is widened when needed so that neighbouring communities do not overlap.

Parameters:

Name Type Description Default
g Graph[Any]

The graph.

required
partition Series

Community id per node, as returned by netviz_tools.metrics.communities.

required
seed int

Seed for the within-community spring layouts.

42
spread float

Smallest radius of the circle of community centres.

4.0

Returns:

Type Description
dict

Node to (x, y).

Other charts

sankey

sankey(
    data: PlotData,
    *,
    color_by: NodeSpec = "auto",
    top_n: int = 10,
    focus: Hashable | Iterable[Hashable] | None = None,
    time: Selector = None,
    category: Selector = None,
    labels: Mapping[str, str] | None = None,
    title: str | None = None,
    height: int = 600,
    seed: int = 42,
    node_attrs: DataFrame | None = None,
) -> Figure

Draw flows from the largest sources (left) to the largest targets (right).

Each node can appear on both sides. Placing sources and targets in separate columns keeps the diagram free of cycles, which a Sankey cannot draw.

Parameters:

Name Type Description Default
data PlotData

A directed NetworkX graph, a flow table, or a mapping from period to graph. One period only: pass time= when the data span several.

required
color_by NodeSpec

Categorical node colour: a node attribute, "community", a mapping, None, or "auto" (communities). Links take the colour of their source.

'auto'
top_n int

Number of sources and of targets to show individually. The rest are grouped into "Other" on each side.

10
focus Hashable | Iterable[Hashable] | None

Node or nodes to follow: only flows touching them are drawn.

None
time Selector

As in network.

None
category Selector

As in network.

None
labels Selector

As in network.

None
title Selector

As in network.

None
height Selector

As in network.

None
seed Selector

As in network.

None
node_attrs Selector

As in network.

None

Returns:

Type Description
Figure

The figure. It is not shown.

Raises:

Type Description
ValueError

If the graph is undirected, the data span several periods, or color_by is numeric.

adjacency

adjacency(
    data: PlotData,
    *,
    sort_by: NodeSpec = "community",
    top_n: int | None = 50,
    focus: Hashable | Iterable[Hashable] | None = None,
    time: Selector = None,
    category: Selector = None,
    labels: Mapping[str, str] | None = None,
    title: str | None = None,
    height: int = 700,
    partition: Series | None = None,
    seed: int = 42,
    node_attrs: DataFrame | None = None,
) -> Figure

Draw the weighted adjacency matrix as a heatmap.

Rows are sources and columns targets. Ordering the nodes by community (the default) makes dense groups show up as blocks along the diagonal; thin lines mark the group boundaries. Cells without an edge are blank, and colours are log-scaled when weights span more than two orders of magnitude. A matrix stays readable where a node-link diagram of a dense graph turns into a hairball.

Parameters:

Name Type Description Default
data PlotData

A NetworkX graph, a flow table, or a mapping from period to graph. One period only.

required
sort_by NodeSpec

Node order: "community" (default), any categorical node attribute or mapping (grouped, groups ordered by size), any numeric attribute or metric (largest first), or None (largest nodes first).

'community'
top_n int | None

Keep the top_n nodes with the largest strength (degree when edges have no weight). None keeps all.

50
focus Hashable | Iterable[Hashable] | None

Node or nodes that are always kept; their row and column labels are drawn in bold.

None
time Selector

As in network.

None
category Selector

As in network.

None
labels Selector

As in network.

None
title Selector

As in network.

None
height Selector

As in network.

None
seed Selector

As in network.

None
node_attrs Selector

As in network.

None
partition Series | None

Community id per node for sort_by="community".

None

Returns:

Type Description
Figure

The figure. It is not shown.

ranking

ranking(
    data: PlotData,
    *,
    size_by: NodeSpec = "auto",
    top_n: int = 15,
    focus: Hashable | Iterable[Hashable] | None = None,
    time: Selector = None,
    category: Selector = None,
    change: bool = False,
    labels: Mapping[str, str] | None = None,
    title: str | None = None,
    height: int | None = None,
    seed: int = 42,
    node_attrs: DataFrame | None = None,
) -> Figure

Rank nodes by a value in a horizontal bar chart.

With one period, bars show the top_n nodes. With several periods, bars show the last period and a grey tick marks each node's value in the period before, so rises and falls are visible at a glance; hover gives both values and the change. With change=True the bars show the change itself (last period minus the one before), sorted by size, increases in blue and decreases in orange.

Parameters:

Name Type Description Default
data PlotData

A NetworkX graph, a flow table, or a mapping from period to graph.

required
size_by NodeSpec

The value to rank by (bar length): a numeric node attribute, a metric such as "out_strength" (for trade data, exports), or a mapping. "auto" is strength, or degree when edges have no weight.

'auto'
top_n int

Number of bars.

15
focus Hashable | Iterable[Hashable] | None

Node or nodes to highlight. They are always shown, even outside the top top_n.

None
time Selector

Periods to use; the last two are compared. None uses all.

None
category Selector

As in network. height defaults to one that fits the bars.

None
labels Selector

As in network. height defaults to one that fits the bars.

None
title Selector

As in network. height defaults to one that fits the bars.

None
height Selector

As in network. height defaults to one that fits the bars.

None
seed Selector

As in network. height defaults to one that fits the bars.

None
node_attrs Selector

As in network. height defaults to one that fits the bars.

None
change bool

Show the change between the last two periods instead of the level.

False

Returns:

Type Description
Figure

The figure. It is not shown.

Raises:

Type Description
ValueError

If change=True and there is only one period, or size_by is not numeric.

compare

compare(
    data: DataFrame,
    focus: Hashable,
    *,
    role: Role = "both",
    category: Selector = None,
    time: Selector = None,
    top_n: int | None = 15,
    labels: Mapping[str, str] | None = None,
    title: str | None = None,
    height: int | None = None,
) -> Figure

Compare what one node sends and receives across categories.

Answers questions such as "which products does this country import, and which does it export?". One row per category; with role="both" the outgoing and incoming totals sit side by side. With several periods the last period is shown, and grey ticks mark the period before.

Parameters:

Name Type Description Default
data DataFrame

A flow table with several categories (for example several FAOSTAT items).

required
focus Hashable

The node to describe.

required
role Role

"out", "in" or "both" (default).

'both'
category Selector

Categories to include. None includes every category the node has flows in.

None
time Selector

Period or periods to use; the last one is shown and the one before is marked. None uses all.

None
top_n int | None

Keep the top_n categories with the largest total. None keeps all.

15
labels Mapping[str, str] | None

As in network.

None
title Mapping[str, str] | None

As in network.

None
height int | None

Figure height in pixels; defaults to one that fits the bars.

None

Returns:

Type Description
Figure

The figure. It is not shown.

Raises:

Type Description
ValueError

If the node has no flows, or the selected categories use more than one unit (they could not share an axis).

time_series

time_series(
    data: DataFrame | Mapping[Hashable, Any],
    columns: Sequence[str] | None = None,
    *,
    focus: Hashable | Iterable[Hashable] | None = None,
    role: Role = "both",
    category: Selector = None,
    time: Selector = None,
    change: bool = False,
    facet: bool = False,
    labels: Mapping[str, str] | None = None,
    title: str | None = None,
    y_title: str | None = None,
    height: int | None = None,
) -> Figure

Plot values over time, one line per series.

Accepts three kinds of input:

  • a table indexed by period, one column per series, such as the output of netviz_tools.temporal.metric_series;
  • a flow table (or a mapping from period to graph): the total weight per period, one line per category;
  • the same with focus=: what the focus node sends and receives per period, for example one country's exports and imports of one item.

Hover shows each value and its change from the previous period.

Parameters:

Name Type Description Default
data DataFrame | Mapping[Hashable, Any]

A period-indexed table, a flow table, or a mapping from period to graph.

required
columns Sequence[str] | None

With a period-indexed table: columns to plot, in legend order. Defaults to all columns.

None
focus Hashable | Iterable[Hashable] | None

With flows: node or nodes to follow.

None
role Role

With focus: "out", "in" or "both" (default).

'both'
category Selector

With flows: category or categories to plot, one line each. None uses all.

None
time Selector

With flows: periods to keep. None keeps all.

None
change bool

Plot the change from the previous period, in percent, instead of the value.

False
facet bool

Draw each series in its own panel with its own y axis. Use this when the series have different units or scales; it avoids a misleading second y axis.

False
labels Mapping[str, str] | None

Display labels, as in network.

None
title str | None

Figure title.

None
y_title str | None

Y-axis title (ignored when facet is true; each panel is titled by its series).

None
height int | None

Figure height in pixels. Defaults to 450, or 220 per panel.

None

Returns:

Type Description
Figure

The figure. It is not shown.

Raises:

Type Description
ValueError

If more than eight series would share one panel. Select fewer, or use facet=True.

degree_distribution

degree_distribution(
    fit: PowerLawFit,
    *,
    labels: Mapping[str, str] | None = None,
    title: str | None = None,
    height: int = 500,
) -> Figure

Plot the empirical CCDF with the fitted power-law, lognormal and exponential tails.

Both axes are logarithmic. Fitted curves start at xmin and are scaled by the tail fraction so that they meet the empirical curve there.

Parameters:

Name Type Description Default
fit PowerLawFit required
labels Mapping[str, str] | None

Display labels; a label for the fitted quantity (for example {"out_strength": "Exports"}) names the x axis.

None
title str | None

Figure title. Defaults to a summary of the fit.

None
height int

Figure height in pixels.

500

Returns:

Type Description
Figure

The figure. It is not shown.

Argument types

PlotData module-attribute

PlotData: TypeAlias = "nx.Graph[Any] | pd.DataFrame | Mapping[Any, nx.Graph[Any]]"

What plot functions accept: a NetworkX graph, a flow table (see netviz_tools.FLOW_COLUMNS), or a mapping from period to graph such as the output of graphs_by(flows, by="time").

Selector module-attribute

Selector: TypeAlias = "Hashable | Iterable[Hashable] | None"

A single value, several values, or None for all.

NodeSpec module-attribute

NodeSpec: TypeAlias = (
    str | Mapping[Any, Any] | pd.Series | None
)

A node attribute name, a NodeMetric name, "auto", a mapping or Series from node to value, or None.

NodeMetric module-attribute

NodeMetric: TypeAlias = Literal[
    "degree",
    "in_degree",
    "out_degree",
    "strength",
    "in_strength",
    "out_strength",
    "pagerank",
    "reverse_pagerank",
    "betweenness",
    "community",
]

Metric names accepted by color_by, size_by and sort_by.

On a directed graph degree and strength count incoming plus outgoing edges. community uses the partition= you pass, or Louvain communities with a fixed seed.

EdgeSpec module-attribute

EdgeSpec: TypeAlias = (
    str | Mapping[tuple[Any, Any], Any] | None
)

An edge attribute name (such as "weight"), "auto", "source" or "target" (edges take the colour of that end node; edge_color_by only), a mapping from (u, v) to value, or None.

ShowLabels module-attribute

ShowLabels: TypeAlias = (
    "bool | int | Sequence[Hashable] | Literal['auto']"
)

"auto" labels every node when there are at most 30, otherwise the 12 largest; an int labels that many of the largest nodes; True/False all or none; a sequence labels exactly those nodes. Focus nodes are always labelled.

Role module-attribute

Role: TypeAlias = Literal['out', 'in', 'both']

Which side of a node's flows to show: what it sends ("out"), what it receives ("in"), or both side by side.

Styling

PALETTE module-attribute

PALETTE: Final = (
    "#2a78d6",
    "#eb6834",
    "#1baf7a",
    "#eda100",
    "#e87ba4",
    "#008300",
    "#4a3aa7",
    "#e34948",
)

Categorical palette in fixed order. It passes adjacent-pair colour-vision deficiency checks; categories beyond eight are folded into "Other".

SEQUENTIAL module-attribute

SEQUENTIAL: Final = (
    (0.0, "#c6dbef"),
    (0.25, "#8fbbe0"),
    (0.5, "#4f93cc"),
    (0.75, "#2166ac"),
    (1.0, "#08306b"),
)

Single-hue sequential colour scale used for continuous values. It starts at a light blue rather than white, so the smallest values stay visible on a white background.

CONTINENT_COLORS module-attribute

CONTINENT_COLORS: Final[Mapping[str, str]] = {
    "Asia": PALETTE[0],
    "Europe": PALETTE[1],
    "Africa": PALETTE[2],
    "Northern America": PALETTE[3],
    "South America": PALETTE[4],
    "Oceania": PALETTE[5],
    "Central America": PALETTE[6],
    "Caribbean": PALETTE[7],
}

Colour per continent, as defined in netviz_tools.datasets.faostat.countries. Used whenever every category of color_by is one of these continents.

DEFAULT_LABELS module-attribute

DEFAULT_LABELS: Final[Mapping[str, str]] = {
    "source": "Source",
    "target": "Target",
    "time": "Time",
    "category": "Category",
    "weight": "Weight",
    "node": "Node",
    "out": "Outgoing",
    "in": "Incoming",
}

Display labels used when neither the data nor the caller gives one. Override any of them with labels=. FAOSTAT flows carry their own (netviz_tools.datasets.faostat.LABELS).

scale

scale(
    values: Iterable[float],
    lo: float,
    hi: float,
    *,
    log: bool = True,
) -> NDArray[float64]

Map values linearly (optionally after log10(1 + x)) onto [lo, hi].

Parameters:

Name Type Description Default
values Iterable[float]

Non-negative numbers.

required
lo float

Output range.

required
hi float

Output range.

required
log bool

Apply log10(1 + x) first, so that a few very large values do not flatten everything else.

True

Returns:

Type Description
ndarray

Scaled values. If all inputs are equal, every output is hi.