Let's try out MPLD3: Bringing Matplotlib to the Browser, which shows tons of promise for extending the reach of matplotlib
into the browser:
The mpld3 project brings together Matplotlib, the popular Python-based graphing library, and D3js, the popular Javascript library for creating data-driven web pages. The result is a simple API for exporting your matplotlib graphics to HTML code which can be used within the browser, within standard web pages, blogs, or tools such as the IPython notebook.
To install mpld3
, you can do a
pip install mpld3
or follow the instructions at jakevdp/mpld3 (essentially, clone the repository and run make install
)
In [5]:
%matplotlib inline
In [2]:
import matplotlib.pyplot as plt
import numpy as np
In [7]:
from mpld3 import enable_notebook
from mpld3 import plugins
enable_notebook()
In [ ]:
# try to import seaborn
try:
import seaborn as sns
except Exception as e:
print "Could not import seaborn", e
In [9]:
# Scatter points
fig, ax = plt.subplots()
np.random.seed(0)
x, y = np.random.normal(0, 1, (2, 200))
color = np.random.random(200)
size = 500 * np.random.random(200)
ax.scatter(x, y, c=color, s=size, alpha=0.3)
ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_title('Matplotlib Plot Rendered in D3!', size=14)
ax.grid(color='lightgray', alpha=0.7)
In [31]:
#Prabha's expt
# ticks change from data format to simple numbers after running mpld3
"""
When plotting daily data, a frequent request is to plot the data
ignoring skips, eg no extra spaces for weekends. This is particularly
common in financial time series, when you may have data for M-F and
not Sat, Sun and you don't want gaps in the x axis. The approach is
to simply use the integer index for the xdata and a custom tick
Formatter to get the appropriate date string for a given index.
"""
from __future__ import print_function
import numpy
from matplotlib.mlab import csv2rec
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.ticker import Formatter
datafile = cbook.get_sample_data('msft.csv', asfileobj=False)
print ('loading %s' % datafile)
r = csv2rec(datafile)[-40:]
class MyFormatter(Formatter):
def __init__(self, dates, fmt='%Y-%m-%d'):
self.dates = dates
self.fmt = fmt
def __call__(self, x, pos=0):
'Return the label for time x at position pos'
ind = int(round(x))
if ind>=len(self.dates) or ind<0: return ''
return self.dates[ind].strftime(self.fmt)
formatter = MyFormatter(r.date)
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(formatter)
ax.plot(numpy.arange(len(r)), r.close, 'o-')
fig.autofmt_xdate()
# #adding tootip
# tooltip = plugins.PointLabelTooltip(scatter, labels=labels)
# plugins.connect(fig, tooltip)
plt.show()
In [66]:
"""
Simple demo of a scatter plot.
"""
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
ax.scatter(x, y, s=area, alpha=0.3)
ax.set_title("Testing Scatter Plot with tooltips!", size=20)
labels = x.tolist()
labels
tooltip = plugins.PointLabelTooltip(scatter, labels=labels)
plugins.connect(fig, tooltip)
# plt.show()
In [62]:
# my expt again
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 100
scatter = ax.scatter(np.random.normal(size=N),
np.random.normal(size=N),
c=np.random.random(size=N),
s = 1000 * np.random.random(size=N),
alpha=0.3,
cmap=plt.cm.jet)
ax.grid(color='white', linestyle='solid')
ax.set_title("Scatter Plot (with tooltips!)", size=20)
x= np.random.rand(N)
labels = x.tolist()
# labels = ['point {0}'.format(i + 1) for i in range(N)]
tooltip = plugins.PointLabelTooltip(scatter, labels=labels)
plugins.connect(fig, tooltip)