Bringing Matplotlib to the Browser

API documentation

«  interactive_legend   ::   Contents

API documentation

Interactive D3 rendering of matplotlib images

Functions: General Use

fig_to_html()
convert a figure to an html string
fig_to_dict()
convert a figure to a dictionary representation
show()
launch a web server to view an d3/html figure representation
save_html()
save a figure to an html file
save_json()
save a JSON representation of a figure to file

Functions: IPython Notebook

display()
display a figure in an IPython notebook
enable_notebook()
enable automatic D3 display of figures in the IPython notebook.
disable_notebook()
disable automatic D3 display of figures in the IPython
mpld3.fig_to_html(fig, d3_url=None, mpld3_url=None, no_extras=False, template_type='general', figid=None, use_http=False, **kwargs)[source]

Output html representation of the figure

Parameters:

fig : matplotlib figure

The figure to display

d3_url : string (optional)

The URL of the d3 library. If not specified, a standard web path will be used.

mpld3_url : string (optional)

The URL of the mpld3 library. If not specified, a standard web path will be used.

no_extras : boolean

If true, remove any extra javascript or CSS. The output will be similar to that if the representation output by fig_to_json is embedded in a web page.

template_type : string

string specifying the type of HTML template to use. Options are:

"simple"

suitable for a simple html page with one figure. Will fail if require.js is available on the page.

"notebook"

assumes require.js and jquery are available.

"general"

more complicated, but works both in and out of the notebook, whether or not require.js and jquery are available

figid : string (optional)

The html/css id of the figure div, which must not contain spaces. If not specified, a random id will be generated.

use_http : boolean (optional)

If true, use http:// instead of https:// for d3_url and mpld3_url.

**kwargs : :

Additional keyword arguments passed to mplexporter.Exporter

Returns:

fig_html : string

the HTML representation of the figure

See also

save_json()
save json representation of a figure to file
save_html()
save html representation of a figure to file
fig_to_dict()
output dictionary representation of the figure
show()
launch a local server and show a figure in a browser
display()
embed figure within the IPython notebook
enable_notebook()
automatically embed figures in IPython notebook
mpld3.fig_to_dict(fig, **kwargs)[source]

Output json-serializable dictionary representation of the figure

Parameters:

fig : matplotlib figure

The figure to display

**kwargs : :

Additional keyword arguments passed to mplexporter.Exporter

Returns:

fig_dict : dict

the Python dictionary representation of the figure, which is directly convertible to json using the standard json package.

See also

save_json()
save json representation of a figure to file
save_html()
save html representation of a figure to file
fig_to_html()
output html representation of the figure
show()
launch a local server and show a figure in a browser
display()
embed figure within the IPython notebook
enable_notebook()
automatically embed figures in IPython notebook
mpld3.fig_to_d3(*args, **kwargs)

mpld3.fig_to_d3 is deprecated: use mpld3.fig_to_html instead

Output html representation of the figure

Parameters:

fig : matplotlib figure

The figure to display

d3_url : string (optional)

The URL of the d3 library. If not specified, a standard web path will be used.

mpld3_url : string (optional)

The URL of the mpld3 library. If not specified, a standard web path will be used.

no_extras : boolean

If true, remove any extra javascript or CSS. The output will be similar to that if the representation output by fig_to_json is embedded in a web page.

template_type : string

string specifying the type of HTML template to use. Options are:

"simple"

suitable for a simple html page with one figure. Will fail if require.js is available on the page.

"notebook"

assumes require.js and jquery are available.

"general"

more complicated, but works both in and out of the notebook, whether or not require.js and jquery are available

figid : string (optional)

The html/css id of the figure div, which must not contain spaces. If not specified, a random id will be generated.

use_http : boolean (optional)

If true, use http:// instead of https:// for d3_url and mpld3_url.

**kwargs : :

Additional keyword arguments passed to mplexporter.Exporter

Returns:

fig_html : string

the HTML representation of the figure

See also

save_json()
save json representation of a figure to file
save_html()
save html representation of a figure to file
fig_to_dict()
output dictionary representation of the figure
show()
launch a local server and show a figure in a browser
display()
embed figure within the IPython notebook
enable_notebook()
automatically embed figures in IPython notebook
mpld3.display_d3(*args, **kwargs)

mpld3.display_d3 is deprecated: use mpld3.display instead

Display figure in IPython notebook via the HTML display hook

Parameters:

fig : matplotlib figure

The figure to display (grabs current figure if missing)

closefig : boolean (default: True)

If true, close the figure so that the IPython matplotlib mode will not display the png version of the figure.

local : boolean (optional, default=False)

if True, then copy the d3 & mpld3 libraries to a location visible to the notebook server, and source them from there. See Notes below.

**kwargs : :

additional keyword arguments are passed through to fig_to_html().

Returns:

fig_d3 : IPython.display.HTML object

the IPython HTML rich display of the figure.

See also

show()
launch a local server and show a figure in a browser
enable_notebook()
automatically embed figures in IPython notebook

Notes

Known issues: using local=True may not work correctly in certain cases:

  • In IPython < 2.0, local=True may fail if the current working directory is changed within the notebook (e.g. with the %cd command).
  • In IPython 2.0+, local=True may fail if a url prefix is added (e.g. by setting NotebookApp.base_url).
mpld3.display(fig=None, closefig=True, local=False, **kwargs)[source]

Display figure in IPython notebook via the HTML display hook

Parameters:

fig : matplotlib figure

The figure to display (grabs current figure if missing)

closefig : boolean (default: True)

If true, close the figure so that the IPython matplotlib mode will not display the png version of the figure.

local : boolean (optional, default=False)

if True, then copy the d3 & mpld3 libraries to a location visible to the notebook server, and source them from there. See Notes below.

**kwargs : :

additional keyword arguments are passed through to fig_to_html().

Returns:

fig_d3 : IPython.display.HTML object

the IPython HTML rich display of the figure.

See also

show()
launch a local server and show a figure in a browser
enable_notebook()
automatically embed figures in IPython notebook

Notes

Known issues: using local=True may not work correctly in certain cases:

  • In IPython < 2.0, local=True may fail if the current working directory is changed within the notebook (e.g. with the %cd command).
  • In IPython 2.0+, local=True may fail if a url prefix is added (e.g. by setting NotebookApp.base_url).
mpld3.show_d3(*args, **kwargs)

mpld3.show_d3 is deprecated: use mpld3.show instead

Open figure in a web browser

Similar behavior to plt.show(). This opens the D3 visualization of the specified figure in the web browser. On most platforms, the browser will open automatically.

Parameters:

fig : matplotlib figure

The figure to display. If not specified, the current active figure will be used.

ip : string, default = ‘127.0.0.1’

the ip address used for the local server

port : int, default = 8888

the port number to use for the local server. If already in use, a nearby open port will be found (see n_retries)

n_retries : int, default = 50

the maximum number of ports to try when locating an empty port.

local : bool, default = True

if True, use the local d3 & mpld3 javascript versions, within the js/ folder. If False, use the standard urls.

open_browser : bool (optional)

if True (default), then open a web browser to the given HTML

http_server : class (optional)

optionally specify an HTTPServer class to use for showing the figure. The default is Python’s basic HTTPServer.

**kwargs : :

additional keyword arguments are passed through to fig_to_html()

See also

display()
embed figure within the IPython notebook
enable_notebook()
automatically embed figures in IPython notebook
mpld3.show(fig=None, ip='127.0.0.1', port=8888, n_retries=50, local=True, open_browser=True, http_server=None, **kwargs)[source]

Open figure in a web browser

Similar behavior to plt.show(). This opens the D3 visualization of the specified figure in the web browser. On most platforms, the browser will open automatically.

Parameters:

fig : matplotlib figure

The figure to display. If not specified, the current active figure will be used.

ip : string, default = ‘127.0.0.1’

the ip address used for the local server

port : int, default = 8888

the port number to use for the local server. If already in use, a nearby open port will be found (see n_retries)

n_retries : int, default = 50

the maximum number of ports to try when locating an empty port.

local : bool, default = True

if True, use the local d3 & mpld3 javascript versions, within the js/ folder. If False, use the standard urls.

open_browser : bool (optional)

if True (default), then open a web browser to the given HTML

http_server : class (optional)

optionally specify an HTTPServer class to use for showing the figure. The default is Python’s basic HTTPServer.

**kwargs : :

additional keyword arguments are passed through to fig_to_html()

See also

display()
embed figure within the IPython notebook
enable_notebook()
automatically embed figures in IPython notebook
mpld3.save_html(fig, fileobj, **kwargs)[source]

Save a matplotlib figure to an html file

Parameters:

fig : matplotlib Figure instance

The figure to write to file.

fileobj : filename or file object

The filename or file-like object in which to write the HTML representation of the figure.

**kwargs : :

additional keyword arguments will be passed to fig_to_html()

See also

save_json()
save json representation of a figure to file
fig_to_html()
output html representation of the figure
fig_to_dict()
output dictionary representation of the figure
mpld3.save_json(fig, fileobj, **kwargs)[source]

Save a matplotlib figure to a json file.

Note that any plugins which depend on generated HTML will not be included in the JSON encoding.

Parameters:

fig : matplotlib Figure instance

The figure to write to file.

fileobj : filename or file object

The filename or file-like object in which to write the HTML representation of the figure.

**kwargs : :

additional keyword arguments will be passed to fig_to_dict()

See also

save_html()
save html representation of a figure to file
fig_to_html()
output html representation of the figure
fig_to_dict()
output dictionary representation of the figure
mpld3.enable_notebook(local=False, **kwargs)[source]

Enable the automatic display of figures in the IPython Notebook.

This function should be used with the inline Matplotlib backend that ships with IPython that can be enabled with %pylab inline or %matplotlib inline. This works by adding an HTML formatter for Figure objects; the existing SVG/PNG formatters will remain enabled.

Parameters:

local : boolean (optional, default=False)

if True, then copy the d3 & mpld3 libraries to a location visible to the notebook server, and source them from there. See Notes below.

**kwargs : :

all keyword parameters are passed through to fig_to_html()

See also

disable_notebook()
undo the action of enable_notebook
display()
embed figure within the IPython notebook
show()
launch a local server and show a figure in a browser

Notes

Known issues: using local=True may not work correctly in certain cases:

  • In IPython < 2.0, local=True may fail if the current working directory is changed within the notebook (e.g. with the %cd command).
  • In IPython 2.0+, local=True may fail if a url prefix is added (e.g. by setting NotebookApp.base_url).
mpld3.disable_notebook()[source]

Disable the automatic display of figures in the IPython Notebook.

See also

enable_notebook()
automatically embed figures in IPython notebook

Plugins to add behavior to mpld3 charts

Plugins are means of adding additional javascript features to D3-rendered matplotlib plots. A number of plugins are defined here; it is also possible to create nearly any imaginable behavior by defining your own custom plugin.

mpld3.plugins.connect(fig, *plugins)[source]

Connect one or more plugins to a figure

Parameters:

fig : matplotlib Figure instance

The figure to which the plugins will be connected

*plugins : :

Additional arguments should be plugins which will be connected to the figure.

Examples

>>> import matplotlib.pyplot as plt
>>> from mpld3 import plugins
>>> fig, ax = plt.subplots()
>>> lines = ax.plot(range(10), '-k')
>>> plugins.connect(fig, plugins.LineLabelTooltip(lines[0]))
mpld3.plugins.clear(fig)[source]

Clear all plugins from the figure, including defaults

mpld3.plugins.get_plugins(fig)[source]

Get the list of plugins in the figure

class mpld3.plugins.Reset[source]

A Plugin to add a reset button

Methods

css()
get_dict()
javascript()
class mpld3.plugins.Zoom(button=True, enabled=None)[source]

A Plugin to add zoom behavior to the plot

Parameters:

button : boolean, optional

if True (default), then add a button to enable/disable zoom behavior

enabled : boolean, optional

specify whether the zoom should be enabled by default. By default, zoom is enabled if button == False, and disabled if button == True.

Notes

Even if enabled is specified, other plugins may modify this state.

Methods

css()
get_dict()
javascript()
class mpld3.plugins.BoxZoom(button=True, enabled=None)[source]

A Plugin to add box-zoom behavior to the plot

Parameters:

button : boolean, optional

if True (default), then add a button to enable/disable zoom behavior

enabled : boolean, optional

specify whether the zoom should be enabled by default. By default, zoom is enabled if button == False, and disabled if button == True.

Notes

Even if enabled is specified, other plugins may modify this state.

Methods

css()
get_dict()
javascript()
class mpld3.plugins.PointLabelTooltip(points, labels=None, hoffset=0, voffset=10, location='mouse')[source]

A Plugin to enable a tooltip: text which hovers over points.

Parameters:

points : matplotlib Collection or Line2D object

The figure element to apply the tooltip to

labels : array or None

If supplied, specify the labels for each point in points. If not supplied, the (x, y) values will be used.

hoffset, voffset : integer

The number of pixels to offset the tooltip text. Default is hoffset = 0, voffset = 10

Examples

>>> import matplotlib.pyplot as plt
>>> from mpld3 import fig_to_html, plugins
>>> fig, ax = plt.subplots()
>>> points = ax.plot(range(10), 'o')
>>> plugins.connect(fig, PointLabelTooltip(points[0]))
>>> fig_to_html(fig)

Methods

css()
get_dict()
javascript()
class mpld3.plugins.PointHTMLTooltip(points, labels=None, hoffset=0, voffset=10, css=None)[source]

A Plugin to enable an HTML tooltip: formated text which hovers over points.

Parameters:

points : matplotlib Collection or Line2D object

The figure element to apply the tooltip to

labels : list

The labels for each point in points, as strings of unescaped HTML.

hoffset, voffset : integer, optional

The number of pixels to offset the tooltip text. Default is hoffset = 0, voffset = 10

css : str, optional

css to be included, for styling the label html if desired

Examples :

——– :

>>> import matplotlib.pyplot as plt :

>>> from mpld3 import fig_to_html, plugins :

>>> fig, ax = plt.subplots() :

>>> points = ax.plot(range(10), ‘o’) :

>>> labels = [‘<h1>{title}</h1>’.format(title=i) for i in range(10)] :

>>> plugins.connect(fig, PointHTMLTooltip(points[0], labels)) :

>>> fig_to_html(fig) :

Methods

css()
get_dict()
javascript()
class mpld3.plugins.LineLabelTooltip(points, label=None, hoffset=0, voffset=10, location='mouse')[source]

A Plugin to enable a tooltip: text which hovers over a line.

Parameters:

line : matplotlib Line2D object

The figure element to apply the tooltip to

label : string

If supplied, specify the labels for each point in points. If not supplied, the (x, y) values will be used.

hoffset, voffset : integer

The number of pixels to offset the tooltip text. Default is hoffset = 0, voffset = 10

Examples

>>> import matplotlib.pyplot as plt
>>> from mpld3 import fig_to_html, plugins
>>> fig, ax = plt.subplots()
>>> lines = ax.plot(range(10), 'o')
>>> plugins.connect(fig, LineLabelTooltip(lines[0]))
>>> fig_to_html(fig)

Methods

css()
get_dict()
javascript()
class mpld3.plugins.MousePosition(fontsize=12, fmt='.3g')[source]

A Plugin to display coordinates for the current mouse position

Methods

css()
get_dict()
javascript()

mpld3 renderer

This is the renderer class which implements the mplexporter framework for mpld3

class mpld3.mpld3renderer.MPLD3Renderer[source]

Renderer class for mpld3

This renderer class plugs into the mplexporter package in order to convert matplotlib figures into a JSON-serializable dictionary representation which can be read by mpld3.js.

Methods

add_data(data[, key]) Add a dataset to the current figure
ax_has_xgrid(ax)
ax_has_ygrid(ax)
ax_zoomable(ax)
close_axes(ax)
close_figure(fig)
close_legend(legend) Finish commands for a particular legend.
datalabel(i)
draw_axes(\*args, \*\*kwds)
draw_figure(\*args, \*\*kwds)
draw_image(imdata, extent, coordinates, style)
draw_legend(\*args, \*\*kwds)
draw_line(data, coordinates, style, label[, ...])
draw_marked_line(data, coordinates, ...[, ...]) Draw a line that also has markers.
draw_markers(data, coordinates, style, label)
draw_path(data, coordinates, pathcodes, style)
draw_path_collection(paths, ...[, mplobj])
draw_text(text, position, coordinates, style)
open_axes(ax, props)
open_figure(fig, props)
open_legend(legend, props) Beging commands for a particular legend.
add_data(data, key='data')[source]

Add a dataset to the current figure

If the dataset matches any already added data, we use that instead.

Parameters:

data : array_like

a shape [N,2] array of data

key : string (optional)

the key to use for the data

Returns:

datadict : dictionary

datadict has the keys “data”, “xindex”, “yindex”, which will be passed to the mpld3 JSON object.

mpld3 Utilities

Utility routines for the mpld3 package

mpld3.utils.deprecated(func, old_name, new_name)[source]

Decorator to mark functions as deprecated.

mpld3.utils.get_id(obj, suffix='', prefix='el', warn_on_invalid=True)[source]

Get a unique id for the object

mpld3.utils.html_id_ok(objid, html5=False)[source]

Check whether objid is valid as an HTML id attribute.

If html5 == True, then use the more liberal html5 rules.

mpld3.utils.write_ipynb_local_js(location=None, d3_src=None, mpld3_src=None)[source]

Write the mpld3 and d3 javascript libraries to the given file location.

This utility is used by the IPython notebook tools to enable easy use of mpld3 with no web connection.

Parameters:

location : string (optioal)

the directory in which the d3 and mpld3 javascript libraries will be written. If not specified, the IPython nbextensions directory will be used. If IPython doesn’t support nbextensions (< 2.0), the current working directory will be used.

d3_src : string (optional)

the source location of the d3 library. If not specified, the standard path in mpld3.urls.D3_LOCAL will be used.

mpld3_src : string (optional)

the source location of the mpld3 library. If not specified, the standard path in mpld3.urls.MPLD3_LOCAL will be used.

Returns:

d3_url, mpld3_url : string

The URLs to be used for loading these js files.

mpld3 URLs

URLs and filepaths for the mpld3 javascript libraries

«  interactive_legend   ::   Contents