Draw interactive NetworkX graphs with Altair

Overview

nx_altair

Draw NetworkX graphs with Altair

Gitter chat

nx_altair offers a similar draw API to NetworkX but returns Altair Charts instead.

If you'd like to contribute, join the Gitter chatroom and share your ideas! Also, checkout the to-do list below.

Examples

If you'd like to start playing with nx_altair, download this notebook!

Simple graph

import networkx as nx
import nx_altair as nxa

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

# Compute positions for viz.
pos = nx.spring_layout(G)

# Draw the graph using Altair
viz = nxa.draw_networkx(G, pos=pos)

# Show it as an interactive plot!
viz.interactive()

Leverage Altair

Customize the visualization

nx_altair also supports many of the same arguments from NetworkX for styling your network--with an Altair twist! Map visualization attributes in a declarative manner.

import numpy as np

# Add weights to nodes and edges
for n in G.nodes():
    G.nodes[n]['weight'] = np.random.randn()

for e in G.edges():
    G.edges[e]['weight'] = np.random.uniform(1, 10)


# Draw the graph using Altair
viz = nxa.draw_networkx(
    G, pos=pos,
    node_color='weight',
    cmap='viridis',
    width='weight',
    edge_color='black',
)

# Show it as an interactive plot!
viz.interactive()

Install

To install from PyPI:

pip install nx_altair

To install for development, clone this repos and install using pip

pip install -e .

Contributing

We welcome pull requests! If you find a bug, we'd love for you to submit a PR. If you're not sure how to do that, check out this simple guide.

If you have a feature request, please open an issue or submit a PR!

Todo list

A list of things to-do (good ideas for PRs).

  • Add draw method that mirrors networkx (easy)
  • Node color scale vmix, vmax (easy)
  • Edge color scale vmix, vmax (easy)
  • Node labels (medium)
  • Edge labels (medium)
  • Mouse-hover interactivity (medium)
  • Arrows for edges (hard)
  • Support for large (>1000 edge) networks (hard)
  • Force-directed interactivity (very hard---beyond altair's current support).
Comments
  • test with real network

    test with real network

    Have you tried to plot a "real" graph, with many nodes? From my experience networkx does not assign the best layout to moderate and large graphs. For example the network of scientists http://networkdata.ics.uci.edu/data/netscience/netscience.gml with spring_layout or kamada_kawai_layout is either odd or with false connectivity.

    opened by empet 6
  • Node Labels

    Node Labels

    I added draw_networkx_nodes_labels to draw_altair.py with the following added parameters:

    • node_label_size : scalar or string Size of nodes (default=15). If an array is specified it must be the same length as nodelist.

    • node_label_color : color string, or array of floats Node color. Can be a single color format string (default='r'), or a sequence of colors with the same length as nodelist. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details.

    • node_label : string The name of the node attribute to treat as a label.

    Limited testing shows that it works as expected, though I haven't yet tested color.

    opened by ryanpeach 5
  • Setting node size

    Setting node size

    Hi, I'm trying, without success, to assign a specific size to each node.

    If I get it right this should be possible by linking the node_size property to a node attribute. Unfortunately, the result is a graph with all nodes represented as dots (size=1 i guess).

    What am I doing wrong?

    Here's my code:

    for n in g.nodes():
        g.nodes[n]['name'] = n
        w = randint(300, 1000)
        g.nodes[n]['size'] = w
        print(w)
        
    pos = nx.spring_layout(g)
    
    viz = nxa.draw_networkx(
        g, 
        pos=pos,
        node_color='#ff0000',
        width='weight',
        edge_color='black',
        node_label='name',
        node_size='size'
    )
    
    viz.interactive()
    
    opened by GiulioRossetti 4
  • Edge Direction

    Edge Direction

    added to_pandas_edges_arrows to core.py which calculates portions of the line to be shown as arrows.

    added draw_networkx_arrows to draw_altair.py which draws the arrows as rectangles on the lines. Added parameters:

    • arrow_width : float, optional (default=2.0) The width of arrow portions of edges.

    • arrow_length : float, optional (default=.25) The proportion of the line to be occupied by the arrow.

    Not dependent on my other pull request. Will require a merge to put them together, only conflict will be in draw_networkx due to the if statements.

    Graphs look similar to a DiGraph in networkx base package plotting. Arrows are only appied if G isinstance nx.DiGraph.

    opened by ryanpeach 3
  • Florentine families example

    Florentine families example

    This is a jupyter notebook that demonstrates how nx_altair can help interpret networks quickly. There is quite a bit of overlap with the existing example in terms of what nx_altair functionality is demonstrated, but I thought it might be helpful to have an example using a real dataset and using networkx functionality to determine colors and sizing.

    opened by SmearingMap 3
  • Ugly default node borders

    Ugly default node borders

    Hi @Zsailer,

    Thanks a lot for your work on this library.

    It seems an Altair or Vega Light update has added default borders that might have not been included in prior versions. When I run the examples on Colab (on right side below) with current Altair 4.1, the network nodes receive distracting blue node outlines, which are not included in the ipynb files generated two years ago.

    ugly default borders

    Is there any chance to make these node borders transparent or width=0?

    All the best & thank you! Marian

    opened by nrchtct 2
  • Fix edge width

    Fix edge width

    Hi guys!

    I've found a small issue with edge width. I've just fixed it, I think it is very clear from code what the problem was, but let me know if you want me to provide some examples before and after the fix.

    As there is not develop branch or similar, I pointing to master, let me know if I should point other branch

    Thansk!

    opened by fpaludi 0
  • Nodes argument of draw_networkx_nodes not respected

    Nodes argument of draw_networkx_nodes not respected

    HI,

    The code below can be found in the method draw_networkx_nodes . I added a line that computes node_chart in the event a subset of nodes is specified via the nodelist argument. Without this line, the entire graph is drawn regardless of the nodelist argument.

       # ---------- Handle arguments ------------
    
        ###### node list argument
        if isinstance(nodelist, list):
            # Subset dataframe.
            df_nodes = df_nodes.loc[nodelist]
            # Build a chart (GE)  <<<<< ADDED THESE TWO LINES
            node_chart = alt.Chart(df_nodes)
    
    opened by erlebach 0
  • florentine_families.ipynb example has errors when used with networkx >= 2.4

    florentine_families.ipynb example has errors when used with networkx >= 2.4

    In networkx >= 2.4, the Graph.node function has been deprecated in favour of Graph.nodes (see https://networkx.org/documentation/stable/release/release_2.4.html#deprecations).

    This means that when using versions of networkx greater or equal to 2.4, when running the florentime_families example notebook, the code chunk pasted below results in an error:

    for f in G.nodes():
        for i, c in enumerate(communities):
            if f in c:
                G.node[f].update({"community" : str(i),
                                    "centrality" : centralities[f],
                                    "name" : f
                                   })
    

    AttributeError: 'Graph' object has no attribute 'node'

    It can be fixed by changing the bit that says G.node[f].update to G.nodes[f].update, though I'm not sure if a bigger change involving refactoring the code a little and using G.set_node_attributes() instead might be a better solution that works on all versions.

    If it'd be helpful, I could submit a PR with one of the suggested fixes?

    opened by thisisnic 0
  • nxa.draw_networkx_edges

    nxa.draw_networkx_edges

    Thanks for the great work! I would like to use nxa.draw_networkx_edges to draw edges with a clorbar, like the graph at https://stackoverflow.com/questions/22124793/colorbar-for-edges-in-networkx. However, I got the following error:

    SchemaValidationError: Invalid specification
    altair.vegalite.v4.schema.core.Scale, validating 'additionalProperties'
    Additional properties are not allowed ('legend' was unexpected)
    

    I would greatly appreciate it if you could help. Thank you!

    Best, Yongcheng

    opened by ycjing 0
  • fixed nodelist and edgelist reference problem

    fixed nodelist and edgelist reference problem

    a = pd.DataFrame([{'a': 1, 'c': 0}, {'a': 2, 'c': 2}, {'a': 3, 'c': 5}]) b = a b = b.loc[[0, 2]]

    b => a c 0 1 0 2 3 5

    a => a c 0 1 0 1 2 2 2 3 5

    opened by jimixxperez 0
Owner
Zachary Sailer
@jupyter core developer, @jupyter Distinguished Contributor
Zachary Sailer
Generate graphs with NetworkX, natively visualize with D3.js and pywebview

webview_d3 This is some PoC code to render graphs created with NetworkX natively using D3.js and pywebview. The main benifit of this approac

byt3bl33d3r 68 Aug 18, 2022
By default, networkx has problems with drawing self-loops in graphs.

By default, networkx has problems with drawing self-loops in graphs. It makes it hard to draw a graph with self-loops or to make a nicely looking chord diagram. This repository provides some code to draw self-loops nicely

Vladimir Shitov 5 Jan 6, 2022
Altair extension for saving charts in a variety of formats.

Altair Saver This packge provides extensions to Altair for saving charts to a variety of output types. Supported output formats are: .json/.vl.json: V

Altair 85 Dec 9, 2022
A high-level plotting API for pandas, dask, xarray, and networkx built on HoloViews

hvPlot A high-level plotting API for the PyData ecosystem built on HoloViews. Build Status Coverage Latest dev release Latest release Docs What is it?

HoloViz 697 Jan 6, 2023
A high-level plotting API for pandas, dask, xarray, and networkx built on HoloViews

hvPlot A high-level plotting API for the PyData ecosystem built on HoloViews. Build Status Coverage Latest dev release Latest release Docs What is it?

HoloViz 349 Feb 15, 2021
Fastest Gephi's ForceAtlas2 graph layout algorithm implemented for Python and NetworkX

ForceAtlas2 for Python A port of Gephi's Force Atlas 2 layout algorithm to Python 2 and Python 3 (with a wrapper for NetworkX and igraph). This is the

Bhargav Chippada 227 Jan 5, 2023
DrawBot lets you draw images taken from the internet on Skribbl.io, Gartic Phone and Paint

DrawBot You don't speak french? No worries, english translation is over here. C'est quoi ? DrawBot est un logiciel codé par V2F qui va prendre possess

V2F 205 Jan 1, 2023
Draw datasets from within Jupyter.

drawdata This small python app allows you to draw a dataset in a jupyter notebook. This should be very useful when teaching machine learning algorithm

vincent d warmerdam 505 Nov 27, 2022
coordinate to draw the nimbus logo on the graffitiwall

This is a community effort to draw the nimbus logo on beaconcha.in's graffitiwall. get started clone repo with git clone https://github.com/tennisbowl

null 4 Apr 4, 2022
Flexitext is a Python library that makes it easier to draw text with multiple styles in Matplotlib

Flexitext is a Python library that makes it easier to draw text with multiple styles in Matplotlib

Tomás Capretto 93 Dec 28, 2022
Draw tree diagrams from indented text input

Draw tree diagrams This repository contains two very different scripts to produce hierarchical tree diagrams like this one: $ ./classtree.py collectio

Luciano Ramalho 8 Dec 14, 2022
BGraph is a tool designed to generate dependencies graphs from Android.bp soong files.

BGraph BGraph is a tool designed to generate dependencies graphs from Android.bp soong files. Overview BGraph (for Build-Graphs) is a project aimed at

Quarkslab 10 Dec 19, 2022
Personal IMDB Graphs with Bokeh

Personal IMDB Graphs with Bokeh Do you like watching movies and also rate all of them in IMDB? Would you like to look at your IMDB stats based on your

null 2 Dec 15, 2021
A D3.js plugin that produces flame graphs from hierarchical data.

d3-flame-graph A D3.js plugin that produces flame graphs from hierarchical data. If you don't know what flame graphs are, check Brendan Gregg's post.

Martin Spier 740 Dec 29, 2022
Here are my graphs for hw_02

Let's Have A Look At Some Graphs! Graph 1: State Mentions in Congressperson's Tweets on 10/01/2017 The graph below uses this data set to demonstrate h

null 7 Sep 2, 2022
Generate knowledge graphs with interesting geometries, like lattices

Geometric Graphs Generate knowledge graphs with interesting geometries, like lattices. Works on Python 3.9+ because it uses cool new features. Get out

Charles Tapley Hoyt 5 Jan 3, 2022
Python ts2vg package provides high-performance algorithm implementations to build visibility graphs from time series data.

ts2vg: Time series to visibility graphs The Python ts2vg package provides high-performance algorithm implementations to build visibility graphs from t

Carlos Bergillos 26 Dec 17, 2022
Flame Graphs visualize profiled code

Flame Graphs visualize profiled code

Brendan Gregg 14.1k Jan 3, 2023
A simple interpreted language for creating basic mathematical graphs.

graphr Introduction graphr is a small language written to create basic mathematical graphs. It is an interpreted language written in python and essent

null 2 Dec 26, 2021