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.disable_notebook()[source]

Disable the automatic display of figures in the IPython Notebook.

See also

enable_notebook()

automatically embed figures in IPython notebook

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.display_d3(fig=None, closefig=True, local=False, **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.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.fig_to_d3(fig, d3_url=None, mpld3_url=None, no_extras=False, template_type='general', figid=None, use_http=False, include_libraries=True, **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.

include_libraries: boolean (optional) :

Whether to inject <script> tag to load JS libraries. Defaults to True.

**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_html(fig, d3_url=None, mpld3_url=None, no_extras=False, template_type='general', figid=None, use_http=False, include_libraries=True, **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.

include_libraries: boolean (optional) :

Whether to inject <script> tag to load JS libraries. Defaults to True.

**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.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.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.show_d3(fig=None, ip='127.0.0.1', port=8888, n_retries=50, local=True, open_browser=True, http_server=None, **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

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.

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.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()

class mpld3.plugins.PointHTMLTooltip(points, labels=None, targets=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.

targets : list

The urls that each point will open when clicked.

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.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.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()

mpld3.plugins.clear(fig)[source]

Clear all plugins from the figure, including defaults

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.get_plugins(fig)[source]

Get the list of plugins in the figure

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)

Finish commands for a particular axes.

close_figure(fig)

Finish commands for a particular figure.

close_legend(legend)

Finish commands for a particular legend.

datalabel(i)

draw_axes(ax, props)

draw_figure(fig, props)

draw_image(imdata, extent, coordinates, style)

Draw an image.

draw_legend(legend, props)

draw_line(data, coordinates, style, label[, ...])

Draw a line.

draw_marked_line(data, coordinates, ...[, ...])

Draw a line that also has markers.

draw_markers(data, coordinates, style, label)

Draw a set of markers.

draw_path(data, coordinates, pathcodes, style)

Draw a path.

draw_path_collection(paths, ...[, mplobj])

Draw a collection of paths.

draw_text(text, position, coordinates, style)

Draw text on the image.

open_axes(ax, props)

Begin commands for a particular axes.

open_figure(fig, props)

Begin commands for a particular figure.

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.

close_axes(ax)[source]

Finish commands for a particular axes.

Parameters:

ax : matplotlib.Axes

The Axes which is finished being drawn.

close_figure(fig)[source]

Finish commands for a particular figure.

Parameters:

fig : matplotlib.Figure

The figure which is finished being drawn.

draw_image(imdata, extent, coordinates, style, mplobj=None)[source]

Draw an image.

Parameters:

imdata : string

base64 encoded png representation of the image

extent : list

the axes extent of the image: [xmin, xmax, ymin, ymax]

coordinates: string :

A string code, which should be either ‘data’ for data coordinates, or ‘figure’ for figure (pixel) coordinates.

style : dictionary

a dictionary specifying the appearance of the image

mplobj : matplotlib object

the matplotlib plot object which generated this image

draw_line(data, coordinates, style, label, mplobj=None)[source]

Draw a line. By default, draw the line via the draw_path() command. Some renderers might wish to override this and provide more fine-grained behavior.

In matplotlib, lines are generally created via the plt.plot() command, though this command also can create marker collections.

Parameters:

data : array_like

A shape (N, 2) array of datapoints.

coordinates : string

A string code, which should be either ‘data’ for data coordinates, or ‘figure’ for figure (pixel) coordinates.

style : dictionary

a dictionary specifying the appearance of the line.

mplobj : matplotlib object

the matplotlib plot element which generated this line

draw_markers(data, coordinates, style, label, mplobj=None)[source]

Draw a set of markers. By default, this is done by repeatedly calling draw_path(), but renderers should generally overload this method to provide a more efficient implementation.

In matplotlib, markers are created using the plt.plot() command.

Parameters:

data : array_like

A shape (N, 2) array of datapoints.

coordinates : string

A string code, which should be either ‘data’ for data coordinates, or ‘figure’ for figure (pixel) coordinates.

style : dictionary

a dictionary specifying the appearance of the markers.

mplobj : matplotlib object

the matplotlib plot element which generated this marker collection

draw_path(data, coordinates, pathcodes, style, offset=None, offset_coordinates='data', mplobj=None)[source]

Draw a path.

In matplotlib, paths are created by filled regions, histograms, contour plots, patches, etc.

Parameters:

data : array_like

A shape (N, 2) array of datapoints.

coordinates : string

A string code, which should be either ‘data’ for data coordinates, ‘figure’ for figure (pixel) coordinates, or “points” for raw point coordinates (useful in conjunction with offsets, below).

pathcodes : list

A list of single-character SVG pathcodes associated with the data. Path codes are one of [‘M’, ‘m’, ‘L’, ‘l’, ‘Q’, ‘q’, ‘T’, ‘t’,

‘S’, ‘s’, ‘C’, ‘c’, ‘Z’, ‘z’]

See the SVG specification for details. Note that some path codes consume more than one datapoint (while ‘Z’ consumes none), so in general, the length of the pathcodes list will not be the same as that of the data array.

style : dictionary

a dictionary specifying the appearance of the line.

offset : list (optional)

the (x, y) offset of the path. If not given, no offset will be used.

offset_coordinates : string (optional)

A string code, which should be either ‘data’ for data coordinates, or ‘figure’ for figure (pixel) coordinates.

mplobj : matplotlib object

the matplotlib plot element which generated this path

draw_path_collection(paths, path_coordinates, path_transforms, offsets, offset_coordinates, offset_order, styles, mplobj=None)[source]

Draw a collection of paths. The paths, offsets, and styles are all iterables, and the number of paths is max(len(paths), len(offsets)).

By default, this is implemented via multiple calls to the draw_path() function. For efficiency, Renderers may choose to customize this implementation.

Examples of path collections created by matplotlib are scatter plots, histograms, contour plots, and many others.

Parameters:

paths : list

list of tuples, where each tuple has two elements: (data, pathcodes). See draw_path() for a description of these.

path_coordinates: string :

the coordinates code for the paths, which should be either ‘data’ for data coordinates, or ‘figure’ for figure (pixel) coordinates.

path_transforms: array_like :

an array of shape (*, 3, 3), giving a series of 2D Affine transforms for the paths. These encode translations, rotations, and scalings in the standard way.

offsets: array_like :

An array of offsets of shape (N, 2)

offset_coordinates : string

the coordinates code for the offsets, which should be either ‘data’ for data coordinates, or ‘figure’ for figure (pixel) coordinates.

offset_order : string

either “before” or “after”. This specifies whether the offset is applied before the path transform, or after. The matplotlib backend equivalent is “before”->”data”, “after”->”screen”.

styles: dictionary :

A dictionary in which each value is a list of length N, containing the style(s) for the paths.

mplobj : matplotlib object

the matplotlib plot element which generated this collection

draw_text(text, position, coordinates, style, text_type=None, mplobj=None)[source]

Draw text on the image.

Parameters:

text : string

The text to draw

position : tuple

The (x, y) position of the text

coordinates : string

A string code, which should be either ‘data’ for data coordinates, or ‘figure’ for figure (pixel) coordinates.

style : dictionary

a dictionary specifying the appearance of the text.

text_type : string or None

if specified, a type of text such as “xlabel”, “ylabel”, “title”

mplobj : matplotlib object

the matplotlib plot element which generated this text

open_axes(ax, props)[source]

Begin commands for a particular axes.

Parameters:

ax : matplotlib.Axes

The Axes which will contain the ensuing axes and elements

props : dictionary

The dictionary of axes properties

open_figure(fig, props)[source]

Begin commands for a particular figure.

Parameters:

fig : matplotlib.Figure

The Figure which will contain the ensuing axes and elements

props : dictionary

The dictionary of figure properties

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.load_test_dataset(dataset)[source]

Loads test data from included CSV files.

Parameters:

dataset : string

The name of the dataset. Available options are: “iris”.

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