In [1]:
%load_ext load_style
%load_style talk.css

Interactive visualisations in the browser with Python

In the past few years, the python (scientific) ecosystem has seen intense development of solutions aimed at bringing interactive data visualisation in the browser, through a set of libraries which basically interface with powerful JavaScript visualisations libraries such as D3.js, rickshaw.js, leaflet.js etc.

In this demo we will see:

In [2]:
import os, sys
import pandas as pd
import numpy as np
from numpy import ma
import matplotlib.pyplot as plt
In [3]:
%matplotlib inline

MPLD3

MPLd3 is developed by Jake VanderPlas

MPLD3 provides a simple API for exporting matplotlib graphics to HTML code which can be used within the browser, within standard web pages, blogs, or tools such as the IPython notebook.

In [4]:
import mpld3
from mpld3 import plugins
mpld3.enable_notebook()
In [5]:
xdf = pd.DataFrame(np.random.normal(size=(100)), columns=['A'])
In [6]:
f, ax= plt.subplots(figsize=(8,4)); 
ax.plot(xdf.index, xdf['A'], lw=2, color='b');
ax.set_xlim(40,80)
ax.grid(color='0.8')

you can connect plugins to the figure

In [7]:
f, ax= plt.subplots(figsize=(8,4)); 
plt.plot(xdf.index, xdf['A'], lw=2, color='b');
ax.set_xlim(40,80)
ax.grid(color='0.8')
plugins.connect(f, plugins.MousePosition(fontsize=16))
In [8]:
mpld3.save_html(f, './mpld3_figure.html')

BOKEH

bokeh is a library developed by continuum analytics

from their website:

Bokeh is a Python interactive visualization library that targets modern web browsers for presentation. Its goal is to provide elegant, concise construction of novel graphics in the style of D3.js, but also deliver this capability with high-performance interactivity over very large or streaming datasets. Bokeh can help anyone who would like to quickly and easily create interactive plots, dashboards, and data applications.

To know more about bokeh:

http://bokeh.pydata.org/

if you use the anaconda python distribution, all the bokeh examples are saved in

${anaconda}/Examples/bokeh 

prepare the data: simple sine

In [9]:
x = np.linspace(0, 10, 1000)
y = np.sin(x)
In [10]:
from bokeh.plotting import figure, output_file, output_notebook, show
BokehJS successfully loaded.
In [11]:
output_notebook()
In [12]:
# create a new plot with a title and axis labels
p = figure(title="simple line example", x_axis_label='x', y_axis_label='y')

# add a line renderer with legend and line thickness
p.line(x, y, legend="sin(x)", line_width=2)

# show the results
show(p)
In [13]:
!open sin.html

Or you can output to an HTML file

**specify mode = "cdn" so it loads the javascript from the bokeh Content Delivery Network instead of the local copy**

In [14]:
output_file("sin.html", title="sin(x)", mode="cdn")

# create a new plot with a title and axis labels
p = figure(title="simple line example", x_axis_label='x', y_axis_label='y')

# add a line renderer with legend and line thickness
p.line(x, y, legend="sin(x)", line_width=2)

# show the results
show(p)
Session output file 'sin.html' already exists, will be overwritten.

You can control the toolbar: here I want pan, box_zoom, rest, but not save etc

In [15]:
x = np.array([0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0])
y0 = x**2
y1 = 10**x
y2 = 10**(x**2)

# output to static HTML file
output_file("log_lines.html")

# create a new plot
p = figure(
   tools="pan,box_zoom,reset",
   y_axis_type="log", y_range=[0.001, 10**11], title="log axis example",
   x_axis_label='sections', y_axis_label='particles'
)

# add some renderers
p.line(x, x, legend="y=x")
p.circle(x, x, legend="y=x", fill_color="white", size=8)
p.line(x, y0, legend="y=x^2", line_width=3)
p.line(x, y1, legend="y=10^x", line_color="red")
p.circle(x, y1, legend="y=10^x", fill_color="red", line_color="red", size=6)
p.line(x, y2, legend="y=10^x^2", line_color="orange", line_dash="4 4")

# show the results
show(p)
Session output file 'log_lines.html' already exists, will be overwritten.

BEARCART

bearcart has been developed by Rob Story and provides an interface to the rickshaw JavaScript library. It does one thing really, which is to plot time series, but it does it (amazingly) well !

In [19]:
import bearcart 
from datetime import datetime
In [20]:
xdf = pd.DataFrame(np.cumsum(np.random.normal(size=(365,3)), axis=0), columns=['A','B','C'], \
                   index=pd.date_range(datetime(1998,1,1,0,0,0), periods=365))
In [21]:
vis = bearcart.Chart(xdf, height=500, width=750, colors={'A':'#FF0000', 'B':'#0066FF', 'C':'#33CC33'})
In [22]:
html_path = r'bearcart.html'
data_path = r'data.json'
js_path = r'rickshaw.min.js'
css_path = r'rickshaw.min.css'
In [23]:
vis.create_chart(html_path=html_path, data_path=data_path, js_path=js_path, css_path=css_path)

Open the url here


FOLIUM

folium has been also been developed by Rob Story to provide an interface to the leaflet.js JavaScript mapping library

In [24]:
import folium
In [25]:
x = np.random.randn(100)

fout = './figure.png'
res = 80
w, h = 4, 2

f, ax = plt.subplots(figsize=(w, h))
ax.fill_between(np.arange(len(x)), 0, x, where=(x>=0), color='r', interpolate=True)
ax.fill_between(np.arange(len(x)), 0, x, where=(x<0), color='b', interpolate=True)
ax.grid(color='.8')
f.savefig('./figure.png', dpi = res)

textpop = """<div align='center'> \
<img src='{}' alt='imaginary temperature anomaly' width='{}' height='{}'> </div>""".format(fout, w*res, h*res)
In [26]:
from map_notebook import * # local functions
In [27]:
map = folium.Map(location=[-13.8333, -171.7500], zoom_start=10) # can also use MapBox tiles if API key
In [28]:
map.circle_marker(location=[-13.8333, -171.7500], popup=textpop, fill_color='#FF0000', line_color=None, radius=3000)
map.circle_marker(location=[-13.9, -171.7400], popup=textpop, fill_color='#FF0000', line_color=None, radius=2000)
In [29]:
inline_map(map)
Out[29]:
In [13]:
map.
In [ ]: