D3 in Jupyter

Brian Coffey
- San Francisco, CA

Jupyter and D3 have both become staples in the data science toolkit: Jupyter for interactive data analysis and D3 for interactive data visualization. There has recently been a growing array of options for using the two together - such as mpld3, bokeh, plotly and others - but these tools usually focus on the use case of a Python or R programmer who would rather not dig too far into JavaScript, and thus somewhat limit the otherwise immense flexibility available with D3. For those who want the full breadth of possibilities, there is another approach shown below. Be sure to play with the force graph!


In [1]:
# import libraries (including our short d3_lib script)
from IPython.core.display import HTML
import d3_lib, random
In [2]:
# construct graph as a set of nodes and links between them
n_nodes = 30
p_edge = 0.05
graph = {"nodes": [], "links": []}
for i in range(n_nodes):
    graph["nodes"].append( {"name": "i" + str(i), "group": int(random.uniform(1,11))} )
for i in range(n_nodes):
    for j in range(n_nodes):
        if random.uniform(0,1) < p_edge and i != j:
            graph["links"].append( {"source": i, "target": j,
                            "value": random.uniform(0.5,3)} )
In [3]:
# visualize as force-directed graph in D3
HTML( d3_lib.set_styles(['force_directed_graph']) + \
      '<script src="lib/d3/d3.min.js"></script>' + \
      d3_lib.draw_graph('force_directed_graph', {'data': graph}) )
Out[3]:



We have developed a short tutorial to walk users through the process of using D3 directly in Jupyter. The code is available in this repo, and the following video presentation and slides from the recent PyData NYC conference walk through the concepts and various examples.


D3 in Jupyter : PyData NYC 2015 from Brian Coffey
Tweet this post! Post on LinkedIn
Multithreaded

Come Work with Us!

We’re a diverse team dedicated to building great products, and we’d love your help. Do you want to build amazing products with amazing peers? Join us!