### Install from GitHub source Source: https://mpld3.github.io/install.html Install from the GitHub repository, requiring an additional step to sync the mplexporter submodule. ```bash [~]$ python setup.py submodule [~]$ python setup.py install ``` -------------------------------- ### Install from source tarball Source: https://mpld3.github.io/install.html Install mpld3 from a downloaded source distribution tarball. ```bash [~]$ python setup.py install ``` -------------------------------- ### Install via pip Source: https://mpld3.github.io/install.html Use the pip installer to install the latest release of mpld3. ```bash [~]$ pip install mpld3 ``` -------------------------------- ### Install from source to custom location Source: https://mpld3.github.io/install.html Install mpld3 from a source distribution to a specific directory using the --prefix flag. ```bash [~]$ python setup.py install --prefix=/path/to/location/ ``` -------------------------------- ### Creating a simple plot Source: https://mpld3.github.io/_downloads/ce3e5a5b6cf72f5547c14f74e967c1b7/custom_plugins.html A basic example to verify that the mpld3 environment is working correctly. ```python np.random.seed(0) plt.plot(np.random.rand(10)); ``` -------------------------------- ### InteractiveLegendPlugin usage example Source: https://mpld3.github.io/_modules/mpld3/plugins.html Example showing how to instantiate and connect an InteractiveLegendPlugin to a matplotlib figure. ```python >>> import matplotlib.pyplot as plt >>> from mpld3 import fig_to_html, plugins >>> N_paths = 5 >>> N_steps = 100 >>> x = np.linspace(0, 10, 100) >>> y = 0.1 * (np.random.random((N_paths, N_steps)) - 0.5) >>> y = y.cumsum(1) >>> fig, ax = plt.subplots() >>> labels = ["a", "b", "c", "d", "e"] >>> line_collections = ax.plot(x, y.T, lw=4, alpha=0.6) >>> interactive_legend = plugins.InteractiveLegendPlugin(line_collections, ... labels, ... alpha_unsel=0.2, ... alpha_over=1.5, ... start_visible=True, ... font_size=14, ... legend_offset=(-100,20)) >>> plugins.connect(fig, interactive_legend) >>> fig_to_html(fig) ``` -------------------------------- ### Initialize Figure with mpld3.draw_figure Source: https://mpld3.github.io/_downloads/8722c12582bbee85f065e941ccb2ece9/sliderPlugin.ipynb Example of calling mpld3.draw_figure with the custom plugin configuration. ```javascript mpld3.draw_figure("fig_el54941400945445260328126322641", {"axes": [{"xlim": [-0.20000000000000001, 1.2000000000000002], "yscale": "linear", "axesbg": "#FFFFFF", "texts": [{"v_baseline": "hanging", "h_anchor": "middle", "color": "#000000", "text": "x [m]", "coordinates": "axes", "zorder": 3, "alpha": 1, "fontsize": 10.0, "position": [0.5, -0.080645161290322578], "rotation": -0.0, "id": "el5494140094544612624"}, {"v_baseline": "auto", "h_anchor": "middle", "color": "#000000", "text": "Deflection [mm]", "coordinates": "axes", "zorder": 3, "alpha": 1, "fontsize": 10.0, "position": [-0.063823084677419359, 0.5], "rotation": -90.0, "id": "el5494140094545512208"}, {"v_baseline": "auto", "h_anchor": "middle", "color": "#000000", "text": "Euler-Bernoulli beam deflection line", "coordinates": "axes", "zorder": 3, "alpha": 1, "fontsize": 12.0, "position": [0.5, 1.0224014336917562], "rotation": -0.0, "id": "el5494140094545727760"}], "zoomable": true, "images": [], "xdomain": [-0.20000000000000001, 1.2000000000000002], "ylim": [-10.0, 5.0], "paths": [], "sharey": [], "sharex": [], "axesbgalpha": null, "axes": [{"scale": "linear", "tickformat": null, "grid": {"color": "#000000", "alpha": 0.2, "dasharray": "2,2", "gridOn": true}, "fontsize": 10.0, "position": "bottom", "nticks": 9, "tickvalues": null}, {"scale": "linear", "tickformat": null, "grid": {"color": "#000000", "alpha": 0.2, "dasharray": "2,2", "gridOn": true}, "fontsize": 10.0, "position": "left", "nticks": 9, "tickvalues": null}], "lines": [{"color": "#000000", "yindex": 1, "coordinates": "data", "dasharray": "10,0", "zorder": 2, "alpha": 0.5, "xindex": 0, "linewidth": 3, "data": "data01", "id": "el5494140094545417424"}, {"color": "#000000", "yindex": 1, "coordinates": "data", "dasharray": "10,0", "zorder": 2, "alpha": 1, "xindex": 0, "linewidth": 1, "data": "data02", "id": "el5494140094545417296"}, {"color": "#000000", "yindex": 1, "coordinates": "data", "dasharray": "10,0", "zorder": 2, "alpha": 1, "xindex": 2, "linewidth": 1, "data": "data02", "id": "el5494140094545418000"}], "markers": [], "id": "el5494140094544526992", "ydomain": [-10.0, 5.0], "collections": [], "xscale": "linear", "bbox": [0.125, 0.125, 0.77500000000000002, 0.77500000000000002]}], "height": 320.0, "width": 640.0, "plugins": [{"type": "reset"}, {"enabled": false, "button": true, "type": "zoom"}, {"enabled": false, "button": true, "type": "boxzoom"}, {"idline": "el5494140094545417424", "type": "myuserinterface", "callback_func": "runCalculation"}], "data": {"data02": [[0.975, -1.0, -0.025], [1.025, -1.0, 0.025], [1.0, 0.0, 0.0], [0.975, -1.0, -0.025]], "data01": [[0.0, -0.0], [0.002004008016032064, -0.037574949095785154], [0.004008016032064128, -0.075148690962674], [0.0060120240480961915, -0.11272001837177029], [0.008016032064128256, -0.1502877240941777], [0.01002004008016032, -0.187850600901], [0.012024048096192383, -0.2254074415633408], [0.014028056112224447, -0.26295703885230387], [0.01603206412825651, -0.300498185538993], ``` -------------------------------- ### Execute exponential fitting example Source: https://mpld3.github.io/_downloads/b6b3dab35511a23d827e98e978a8699e/custom_widgin_general.html Initializes the Fit class with an exponential function and performs an initial redraw. ```python # click and drag not active here, we just show how we fit def exp_ech(x, params): return params[0] * (1 - np.exp(-params[1] * x)) # we ensure we will fit nicely by setting p[0] at [0,0] # in effect adding one degree of liberty Fit(exp_ech).redraw("0,0,0") ``` ```text we have 2 parameters ``` -------------------------------- ### Using PointLabelTooltip Source: https://mpld3.github.io/_downloads/ce3e5a5b6cf72f5547c14f74e967c1b7/custom_plugins.html Example of connecting a PointLabelTooltip plugin to a scatter plot to display information on hover. ```python fig, ax = plt.subplots() points = ax.scatter(np.random.rand(40), np.random.rand(40), s=300, alpha=0.3) labels = ["Point {0}".format(i) for i in range(40)] tooltip = plugins.PointLabelTooltip(points, labels) plugins.connect(fig, tooltip) ``` -------------------------------- ### Random walk visualization with custom hover-highlight plugin (random_walk.py) Source: https://mpld3.github.io/examples/random_walk.html Full example from random_walk.py. It defines a HighlightLines plugin that uses mpld3's PluginBase and a JavaScript prototype to change stroke opacity on mouseover/mouseout. The script generates 50 random walks of 100 steps, plots them with alpha=0.1, connects the plugin, and calls mpld3.show(). ```python Visualizing Random Walks ======================== This shows the use of transparent lines to visualize random walk data. There is also a custom plugin defined which causes lines to be highlighted when the mouse hovers over them. Use the toolbar buttons at the bottom-right of the plot to enable zooming and panning, and to reset the view. """ import jinja2 import json import numpy as np import matplotlib.pyplot as plt import mpld3 from mpld3 import plugins, utils class HighlightLines(plugins.PluginBase): """A plugin to highlight lines on hover""" JAVASCRIPT = """ mpld3.register_plugin("linehighlight", LineHighlightPlugin); LineHighlightPlugin.prototype = Object.create(mpld3.Plugin.prototype); LineHighlightPlugin.prototype.constructor = LineHighlightPlugin; LineHighlightPlugin.prototype.requiredProps = ["line_ids"]; LineHighlightPlugin.prototype.defaultProps = {alpha_bg:0.3, alpha_fg:1.0} function LineHighlightPlugin(fig, props){ mpld3.Plugin.call(this, fig, props); }; LineHighlightPlugin.prototype.draw = function(){ for(var i=0; i>> 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) ``` -------------------------------- ### PointHTMLTooltip Usage Example Source: https://mpld3.github.io/_modules/mpld3/plugins.html Demonstrates how to connect a PointHTMLTooltip to a matplotlib plot and convert it to HTML. ```python >>> import matplotlib.pyplot as plt >>> from mpld3 import fig_to_html, plugins >>> fig, ax = plt.subplots() >>> points = ax.plot(range(10), 'o') >>> labels = ['

{title}

'.format(title=i) for i in range(10)] >>> plugins.connect(fig, PointHTMLTooltip(points[0], labels)) >>> fig_to_html(fig) ``` -------------------------------- ### Displaying a Matplotlib Figure Source: https://mpld3.github.io/_downloads/bb1d34beaf7997748dc78d5d25947757/custom_plugins.ipynb An example of rendering a Matplotlib figure within the notebook environment. ```python 4GYqLXThyZDs0mvC3bqQ2jqj6+Bsb G2E0GmEwGAAAR48excmTJ1FcXDzT5qOPPsKxY8cAANXV1RgdHYXD4YBWq43mpall5vV6wTBSCIVC EOIBISTsbgChUIL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LCyX29vZ2snv3buL3+4nb7SYmk4m0trbGKOLZQon/17/+NXnmmWcI YQMDAwQnU5HhoeHYxHuvG7duhXS4O5aO26/s1j8kRy3MUn8w8PDZPfu3SQ/P5/U1tYSl8tFCCHE ZrORAwcOEEII+eqrrwjDMKS8vJxUVFSQiooKcvr06ViEO+PUqVOkoKCA5OXlkeeee44QQsgrr7xC XnnllZk2v/rVr0heXh4pKysjV69ejVWo81oq/kceeYSoVKqZz3vr1q2xDHeOUD7/76ylxE9IjnE+ 9gAAAI5JREFUaLH/+c9/JiUlJcRkMpGXXnopVqHOa6n4nU4nuf/++0lZWRkxmUzkzTffjGW4sxw9 epSkp6cToVBI9Ho9ee2119bVcbtU/JEct3QBF0VRVJyhWy9SFEXFGZr4KYqi4gxN/BRFUXGGJn6K oqg4QxM/RVFUnKGJn6IoKs7QxE9RFBVnaOKnKIqKM/8fygYaMZb1VSQAAAAASUVORK5CYII= ``` -------------------------------- ### show() Source: https://mpld3.github.io/modules/API.html Launches a web server to view a D3/HTML figure representation in a browser. ```APIDOC ## show() ### Description Launch a web server to view an d3/html figure representation. ### Method Function call ### Endpoint show(fig, **kwargs) ### Parameters #### Function Parameters - **fig** (matplotlib figure) - Required - The figure to display. - **kwargs** - Optional - Additional keyword arguments passed to the underlying conversion function. ### Returns None ### Example ```python import mpld3 fig = plt.figure() mpld3.show(fig) ``` ``` -------------------------------- ### mpld3.utils.get_id Source: https://mpld3.github.io/modules/API.html Get a unique id for the object. ```APIDOC ## mpld3.utils.get_id ### Description Get a unique id for the object. ### Method Function ### Signature mpld3.utils.get_id(_obj_, _suffix=''_, _prefix='el'_, _warn_on_invalid=True_) ### Parameters - **obj** (object) - Required - The object for which to generate an id. - **suffix** (string) - Optional - Suffix to append to the id. Default is ''. - **prefix** (string) - Optional - Prefix to prepend to the id. Default is 'el'. - **warn_on_invalid** (bool) - Optional - Whether to warn if the id is invalid. Default is True. ### Returns - A unique id string for the object. ``` -------------------------------- ### Define MyUserInterfacePlugin Constructor and Prototype Source: https://mpld3.github.io/_downloads/8722c12582bbee85f065e941ccb2ece9/sliderPlugin.ipynb Sets up the plugin prototype, required properties, and constructor function. ```javascript MyUserInterfacePlugin.prototype.constructor = MyUserInterfacePlugin; MyUserInterfacePlugin.prototype.requiredProps = ["idline", "callback_func"]; MyUserInterfacePlugin.prototype.defaultProps = {} function MyUserInterfacePlugin(fig, props){ mpld3.Plugin.call(this, fig, props); }; ``` -------------------------------- ### LineHTMLTooltip Usage Example Source: https://mpld3.github.io/_modules/mpld3/plugins.html Demonstrates how to connect a LineHTMLTooltip to a matplotlib line plot. ```python >>> import matplotlib.pyplot as plt >>> from mpld3 import fig_to_html, plugins >>> fig, ax = plt.subplots() >>> lines = ax.plot(range(10)) >>> label = '

line {title}

'.format(title='A') >>> plugins.connect(fig, LineHTMLTooltip(lines[0], label)) >>> fig_to_html(fig) ``` -------------------------------- ### Configure and load mpld3 libraries Source: https://mpld3.github.io/_downloads/bb1d34beaf7997748dc78d5d25947757/custom_plugins.ipynb Initializes the d3 library path and loads the mpld3 library using require.js. ```javascript require.config({paths: {d3: "https://mpld3.github.io/js/d3.v3.min"}}); require(["d3"], function(d3){ window.d3 = d3; mpld3_load_lib("https://mpld3.github.io/js/mpld3.v0.2git.js", function(){ ``` -------------------------------- ### Opening figures in a browser with show() Source: https://mpld3.github.io/_modules/mpld3/_display.html Launches a local web server to display a Matplotlib figure in the default web browser using D3.js. ```python def show(fig=None, ip='127.0.0.1', port=8888, n_retries=50, local=True, open_browser=True, http_server=None, **kwargs): """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 :func:`fig_to_html` See Also -------- :func:`display` : embed figure within the IPython notebook :func:`enable_notebook` : automatically embed figures in IPython notebook """ if local: kwargs['mpld3_url'] = '/mpld3.js' kwargs['d3_url'] = '/d3.js' files = {'/mpld3.js': ["text/javascript", open(urls.MPLD3_LOCAL, 'r').read()], '/d3.js': ["text/javascript", open(urls.D3_LOCAL, 'r').read()]} else: files = None if fig is None: # import here, in case matplotlib.use(...) is called by user import matplotlib.pyplot as plt fig = plt.gcf() html = fig_to_html(fig, **kwargs) serve(html, ip=ip, port=port, n_retries=n_retries, files=files, open_browser=open_browser, http_server=http_server) ``` -------------------------------- ### Define custom HelloWorld plugin with JavaScript Source: https://mpld3.github.io/notebooks/custom_plugins.html Defines a custom mpld3 plugin class that inherits from PluginBase and includes a JAVASCRIPT string. The JavaScript registers the plugin and draws 'hello world' text on the figure. The plugin is then connected to a figure. ```python class HelloWorld(plugins.PluginBase): # inherit from PluginBase """Hello World plugin""" JAVASCRIPT = """ mpld3.register_plugin("helloworld", HelloWorld); HelloWorld.prototype = Object.create(mpld3.Plugin.prototype); HelloWorld.prototype.constructor = HelloWorld; function HelloWorld(fig, props){ mpld3.Plugin.call(this, fig, props); }; HelloWorld.prototype.draw = function(){ this.fig.canvas.append("text") .text("hello world") .style("font-size", 72) .style("opacity", 0.3) .style("text-anchor", "middle") .attr("x", this.fig.width / 2) .attr("y", this.fig.height / 2) } """ def __init__(self): self.dict_ = {"type": "helloworld"} fig, ax = plt.subplots() plugins.connect(fig, HelloWorld()) ``` -------------------------------- ### Register the HelloWorld plugin with mpld3.register_plugin Source: https://mpld3.github.io/_downloads/ce3e5a5b6cf72f5547c14f74e967c1b7/custom_plugins.html Associates the key 'helloworld' with the HelloWorld plugin object so it can be referenced in the figure JSON. ```javascript mpld3.register_plugin("helloworld", HelloWorld); ``` -------------------------------- ### Connecting NetworkXD3ForceLayout to Matplotlib Source: https://mpld3.github.io/examples/networkxd3forcelayout.html Example usage of connecting the NetworkXD3ForceLayout plugin to a matplotlib figure and displaying it. ```python import matplotlib.pyplot as plt fig, axs = plt.subplots(1, 1, figsize=(10, 10)) ax = axs mpld3.plugins.connect(fig, NetworkXD3ForceLayout(graph, ax, gravity=.5, link_distance=20, charge=-600, friction=1 ) ) mpld3.show() ``` -------------------------------- ### Connecting custom plugins to a figure Source: https://mpld3.github.io/_downloads/ce3e5a5b6cf72f5547c14f74e967c1b7/custom_plugins.html Demonstrates how to manually add and reorder interactive tools like Reset, BoxZoom, and Zoom using plugins.connect. ```python from mpld3 import plugins fig, ax = plt.subplots() ax.plot(np.random.random(10)) plugins.clear(fig) # clear all plugins from the figure plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom()) ``` -------------------------------- ### PluginBase Source: https://mpld3.github.io/_modules/mpld3/plugins.html Base class for creating the plugin. Contains methods to get the dictionary and javascript/css of the plugin. ```APIDOC ## PluginBase ### Description Base class for a plugin. It provides methods to render the plugin's dictionary representation and its JavaScript and CSS. ### Methods - **get_dict()** - Returns the dictionary of the plugin. - **javascript()** - Returns the JavaScript string if defined, otherwise an empty string. - **css()** - Returns the CSS string if defined, otherwise an empty string. ``` -------------------------------- ### Output of utils.get_id Source: https://mpld3.github.io/_downloads/ce3e5a5b6cf72f5547c14f74e967c1b7/custom_plugins.html Example output of utils.get_id(points), showing the generated id string that is passed to the plugin. ```text 'el92644400590224' ``` -------------------------------- ### mpld3 Figure Initialization Source: https://mpld3.github.io/_downloads/bb1d34beaf7997748dc78d5d25947757/custom_plugins.ipynb Initializes an mpld3 figure with the HelloWorld plugin enabled. ```javascript mpld3.draw_figure("fig_el926444003186726333897603", {"axes": [{"xlim": [0.0, 1.0], "yscale": "linear", "axesbg": "#FFFFFF", "texts": [], "zoomable": true, "images": [], "xdomain": [0.0, 1.0], "ylim": [0.0, 1.0], "paths": [], "sharey": [], "sharex": [], "axesbgalpha": null, "axes": [{"scale": "linear", "tickformat": null, "grid": {"gridOn": false}, "fontsize": 10.0, "position": "bottom", "nticks": 6, "tickvalues": null}, {"scale": "linear", "tickformat": null, "grid": {"gridOn": false}, "fontsize": 10.0, "position": "left", "nticks": 6, "tickvalues": null}], "lines": [], "markers": [], "id": "el92644400026640", "ydomain": [0.0, 1.0], "collections": [], "xscale": "linear", "bbox": [0.125, 0.125, 0.77500000000000002, 0.77500000000000002]}], "height": 320.0, "width": 480.0, "plugins": [{"type": "reset"}, {"enabled": false, "button": true, "type": "zoom"}, {"enabled": false, "button": true, "type": "boxzoom"}, {"type": "helloworld"}], "data": {}, "id": "el92644400318672"}); }); }); }else{ // require.js not available: dynamically load d3 & mpld3 mpld3_load_lib("https://mpld3.github.io/js/d3.v3.min.js", function(){ mpld3_load_lib("https://mpld3.github.io/js/mpld3.v0.2git.js", function(){ mpld3.register_plugin("helloworld", HelloWorld); HelloWorld.prototype = Object.create(mpld3.Plugin.prototype); HelloWorld.prototype.constructor = HelloWorld; function HelloWorld(fig, props){ mpld3.Plugin.call(this, fig, props); }; HelloWorld.prototype.draw = function(){ this.fig.canvas.append("text") .text("hello world") .style("font-size", 72) .style("opacity", 0.3) .style("text-anchor", "middle") .attr("x", this.fig.width / 2) .attr("y", this.fig.height / 2) } mpld3.draw_figure("fig_el926444003186726333897603", {"axes": [{"xlim": [0.0, 1.0], "yscale": "linear", "axesbg": "#FFFFFF", "texts": [], "zoomable": true, "images": [], "xdomain": [0.0, 1.0], "ylim": [0.0, 1.0], "paths": [], "sharey": [], "sharex": [], "axesbgalpha": null, "axes": [{"scale": "linear", "tickformat": null, "grid": {"gridOn": false}, "fontsize": 10.0, "position": "bottom", "nticks": 6, "tickvalues": null}, {"scale": "linear", "tickformat": null, "grid": {"gridOn": false}, "fontsize": 10.0, "position": "left", "nticks": 6, "tickvalues": null}], "lines": [], "markers": [], "id": "el92644400026640", "ydomain": [0.0, 1.0], "collections": [], "xscale": "linear", "bbox": [0.125, 0.125, 0.77500000000000002, 0.77500000000000002]}], "height": 320.0, "width": 480.0, "plugins": [{"type": "reset"}, {"enabled": false, "button": true, "type": "zoom"}, {"enabled": false, "button": true, "type": "boxzoom"}, {"type": "helloworld"}], "data": {}, "id": "el92644400318672"}); }) }); } ``` -------------------------------- ### Configure Python Figure and Connect Plugin Source: https://mpld3.github.io/_downloads/8722c12582bbee85f065e941ccb2ece9/sliderPlugin.ipynb Sets up a matplotlib figure with a line object and connects it to a custom MyUserInterface plugin. ```python y = -v(x, a)*1000.0 return map(list, list(zip(list(x), list(y)))) fig, ax = plt.subplots(figsize=(8, 4)) t = np.linspace(0, 1, 200) y = np.sin(t) ax.set_xlabel('x [m]') ax.set_ylabel('Deflection [mm]') ax.set_title('Euler-Bernoulli beam deflection line') # create the line object initial_data = np.array(runCalculation(0.5)) line, = ax.plot(initial_data[:, 0], initial_data[:, 1], '-k', lw=3, alpha=0.5) ax.plot([0.975, 1.025, 1.00, 0.975], [-1, -1, 0, -1], '-k', lw=1) ax.plot([-0.025, 0.025, 0.000, -0.025], [-1, -1, 0, -1], '-k', lw=1) ax.set_ylim(-10, 5) ax.grid(lw=0.1, alpha=0.2) mpld3.plugins.connect(fig, MyUserInterface(line, callback_func="runCalculation")) ``` -------------------------------- ### LinkedBrush usage Source: https://mpld3.github.io/_modules/mpld3/plugins.html Example showing how to enable linked brushing between multiple scatter plots. Note that data must not contain NaNs for this to function correctly. ```python >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from mpld3 import fig_to_html, plugins >>> X = np.random.random((3, 100)) >>> fig, ax = plt.subplots(3, 3) >>> for i in range(2): ... for j in range(2): ... points = ax[i, j].scatter(X[i], X[j]) >>> plugins.connect(fig, LinkedBrush(points)) >>> fig_to_html(fig) ``` -------------------------------- ### Get element id with utils.get_id Source: https://mpld3.github.io/_downloads/ce3e5a5b6cf72f5547c14f74e967c1b7/custom_plugins.html Generates the unique id for the points object. This id is used in the plugin's dict_ and later to locate the corresponding JavaScript element. ```python utils.get_id(points) ```