
上QQ阅读APP看书,第一时间看更新
Visualizing with d3.js via mpld3
D3.js is a JavaScript data visualization library released in 2011, which we can also use in an IPython notebook. We will add hovering tooltips to a regular matplotlib plot. As a bridge, we need the mpld3
package. This recipe doesn't require any JavaScript coding whatsoever.
Getting ready
I installed mpld3 0.2 with the following command:
$ [sudo] pip install mpld3
How to do it...
- Start with the imports and enable mpld3:
%matplotlib inline import matplotlib.pyplot as plt import mpld3 mpld3.enable_notebook() from mpld3 import plugins import seaborn as sns from dautil import data from dautil import ts
- Load the weather data and plot it as follows:
df = data.Weather.load() df = df[['TEMP', 'WIND_SPEED']] df = ts.groupby_yday(df).mean() fig, ax = plt.subplots() ax.set_title('Averages Grouped by Day of Year') points = ax.scatter(df['TEMP'], df['WIND_SPEED'], s=30, alpha=0.3) ax.set_xlabel(data.Weather.get_header('TEMP')) ax.set_ylabel(data.Weather.get_header('WIND_SPEED')) labels = ["Day of year {0}".format(i) for i in range(366)] tooltip = plugins.PointLabelTooltip(points, labels) plugins.connect(fig, tooltip)
The highlighted lines are responsible for the tooltips. In the following screenshot, the Day of year 31 text comes from the tooltip:

As you can see, at the bottom of the plot, you also have widgets for panning and zooming (refer to the mpld3_demo.ipynb
file in this book's code bundle).