How to use mpld3 - 10 common examples

To help you get started, we’ve selected a few mpld3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github kjyv / FloBaRoID / identification / output.py View on Github external
if idf.opt['outputAs'] == 'html':
                    #TODO: show legend properly (see mpld3 bug #274)
                    #leg = fig.legend(handles, labels, loc='upper right', fancybox=True, fontsize=10, title='')
                    leg = axes[0].legend(handles, labels, loc='upper right', fancybox=True, fontsize=10, title='', prop={'size': 8})
                else:
                    leg = plt.figlegend(handles, labels, loc='upper right', fancybox=True,
                            fontsize=font_size, title='', prop={'size': font_size-3})
                    leg.draggable()

            fig.subplots_adjust(hspace=2)
            fig.set_tight_layout(True)

            if idf.opt['outputAs'] == 'html':
                plugins.clear(fig)
                plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom(enabled=False),
                                plugins.MousePosition(fontsize=14, fmt=".5g"))
                figures.append(mpld3.fig_to_html(fig))
            elif idf.opt['outputAs'] == 'interactive':
                plt.show(block=False)
            elif idf.opt['outputAs'] == 'pdf':
                pp.savefig(plt.gcf())
            elif idf.opt['outputAs'] == 'tikz':
                from matplotlib2tikz import save as tikz_save
                tikz_save('{}_{}_{}.tex'.format(filename,
                    group['dataset'][0]['title'].replace('_','-'), ds // idf.model.num_dofs),
                    figureheight = '\\figureheight', figurewidth = '\\figurewidth', show_info=False)

        if idf.opt['outputAs'] == 'html':
            path = os.path.dirname(os.path.abspath(__file__))
            template_environment = Environment(autoescape=False,
                                               loader=FileSystemLoader(os.path.join(path, '../output')),
                                               trim_blocks=False)
github kjyv / FloBaRoID / identification / output.py View on Github external
if idf.opt['plotLegend']:
                handles, labels = ax.get_legend_handles_labels()
                if idf.opt['outputAs'] == 'html':
                    #TODO: show legend properly (see mpld3 bug #274)
                    #leg = fig.legend(handles, labels, loc='upper right', fancybox=True, fontsize=10, title='')
                    leg = axes[0].legend(handles, labels, loc='upper right', fancybox=True, fontsize=10, title='', prop={'size': 8})
                else:
                    leg = plt.figlegend(handles, labels, loc='upper right', fancybox=True,
                            fontsize=font_size, title='', prop={'size': font_size-3})
                    leg.draggable()

            fig.subplots_adjust(hspace=2)
            fig.set_tight_layout(True)

            if idf.opt['outputAs'] == 'html':
                plugins.clear(fig)
                plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom(enabled=False),
                                plugins.MousePosition(fontsize=14, fmt=".5g"))
                figures.append(mpld3.fig_to_html(fig))
            elif idf.opt['outputAs'] == 'interactive':
                plt.show(block=False)
            elif idf.opt['outputAs'] == 'pdf':
                pp.savefig(plt.gcf())
            elif idf.opt['outputAs'] == 'tikz':
                from matplotlib2tikz import save as tikz_save
                tikz_save('{}_{}_{}.tex'.format(filename,
                    group['dataset'][0]['title'].replace('_','-'), ds // idf.model.num_dofs),
                    figureheight = '\\figureheight', figurewidth = '\\figurewidth', show_info=False)

        if idf.opt['outputAs'] == 'html':
            path = os.path.dirname(os.path.abspath(__file__))
            template_environment = Environment(autoescape=False,
github kjyv / FloBaRoID / identification / output.py View on Github external
handles, labels = ax.get_legend_handles_labels()
                if idf.opt['outputAs'] == 'html':
                    #TODO: show legend properly (see mpld3 bug #274)
                    #leg = fig.legend(handles, labels, loc='upper right', fancybox=True, fontsize=10, title='')
                    leg = axes[0].legend(handles, labels, loc='upper right', fancybox=True, fontsize=10, title='', prop={'size': 8})
                else:
                    leg = plt.figlegend(handles, labels, loc='upper right', fancybox=True,
                            fontsize=font_size, title='', prop={'size': font_size-3})
                    leg.draggable()

            fig.subplots_adjust(hspace=2)
            fig.set_tight_layout(True)

            if idf.opt['outputAs'] == 'html':
                plugins.clear(fig)
                plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom(enabled=False),
                                plugins.MousePosition(fontsize=14, fmt=".5g"))
                figures.append(mpld3.fig_to_html(fig))
            elif idf.opt['outputAs'] == 'interactive':
                plt.show(block=False)
            elif idf.opt['outputAs'] == 'pdf':
                pp.savefig(plt.gcf())
            elif idf.opt['outputAs'] == 'tikz':
                from matplotlib2tikz import save as tikz_save
                tikz_save('{}_{}_{}.tex'.format(filename,
                    group['dataset'][0]['title'].replace('_','-'), ds // idf.model.num_dofs),
                    figureheight = '\\figureheight', figurewidth = '\\figurewidth', show_info=False)

        if idf.opt['outputAs'] == 'html':
            path = os.path.dirname(os.path.abspath(__file__))
            template_environment = Environment(autoescape=False,
                                               loader=FileSystemLoader(os.path.join(path, '../output')),
github Patent2net / P2N / Patent2Net / P2N-Cluster.py View on Github external
// then change the y position to be
      // at the top of the figure
      this.fig.toolbar.toolbar.attr("x", 1200);
      this.fig.toolbar.toolbar.attr("y", 310);

      // then remove the draw function,
      // so that it is not called again
      this.fig.toolbar.draw = function() {}
    }
    
    """
    def __init__(self):
        self.dict_ = {"type": "toptoolbar"}
        
class ClickInfo(mpld3.plugins.PluginBase):
    """Hack of mpld3 Plugin for getting info on click adding "on mouse over" tooltip function   """

    JAVASCRIPT = """
    mpld3.register_plugin("ClickInfo", ClickInfo);
    ClickInfo.prototype = Object.create(mpld3.Plugin.prototype);
    ClickInfo.prototype.constructor = ClickInfo;
    ClickInfo.prototype.requiredProps = ["id", "urls", "labels"];
    ClickInfo.prototype.defaultProps = {hoffset:10,
                                                voffset:10};
        
    function ClickInfo(fig, props){
        mpld3.Plugin.call(this, fig, props);
    };

    ClickInfo.prototype.draw = function(){
        var obj = mpld3.get_element(this.props.id);
github svenkreiss / databench_examples / analyses / mpld3PointLabel / analysis.py View on Github external
def on_connect(self):
        """Run as soon as a browser connects to this."""

        fig, ax = plt.subplots()
        points = ax.scatter(
            np.random.rand(40),
            np.random.rand(40),
            s=300,
            alpha=0.3,
        )

        # use the mpld3 tooltop plugin
        labels = ["Point {0}".format(i) for i in range(40)]
        tooltip = mpld3.plugins.PointLabelTooltip(points, labels)
        mpld3.plugins.connect(fig, tooltip)

        # send the plot to the frontend
        self.emit('mpld3canvas', mpld3.fig_to_dict(fig))

        # done
        self.emit('log', {'action': 'done'})
github HybriD3-database / MatD3 / materials / plotting / pl_plotting.py View on Github external
# print(x[min_index])
    # Xlim = maxXlim - minXlim
    # ax.axhline(y=1, xmin=(x[peak_index]-minXlim)/Xlim, ls='--', color='r')
    # ax.axhline(y=0, xmin=(x[min_index]-minXlim)/Xlim, ls='--', color='r')

    # print points[0]
    labels = []
    for i,j in zip(x,y):
        label = '<div class="tooltiptext">'
        label += '{2}: {1} <br> {3}: {0}'.format(i, j, y_label, x_label)
        label += '</div>'
        labels.append(label)

    tooltip = plugins.PointHTMLTooltip(points[0], labels, hoffset=-tooltipwidth/2, voffset=-tooltipheight, css=css)

    plugins.connect(fig, tooltip)

    save_name = "{}.html".format(filename.split(".")[0])
    # filename = "{}.png".format(filename.split(".")[0])
    # plt.savefig(filename, dpi = 300, bbox_inches='tight')
    mpld3.save_html(fig, save_name)
    plt.close()
    # mpld3.fig_to_html(plt_figure)
github ratschlab / spladder / matlab / spladder_viz.py View on Github external
event_info = [x[::-1] for x in re.split(r'[._]', options.event_id[::-1], maxsplit=1)[::-1]]
            event_info[1] = int(event_info[1]) - 1
            event_info = sp.array(event_info, dtype='str')[sp.newaxis, :]
            event_tag = '.%s' % options.event_id
        ### get all significant events of the current gene
        else:
            event_info = get_conf_events(options, gid)
            
        plot_event(options, event_info, axes[-1], xlim)

        plt.tight_layout()
        ### save plot into file
        if options.format == 'd3':
            out_fname = os.path.join(options.outdir, 'plots', 'gene_overview_%s%s%s.html' % (gene.name, event_tag, log_tag))
            plugins.clear(fig)
            plugins.connect(fig, plugins.Zoom(enabled=True), ClickInfo(sp.ones((10000,), dtype='int')))
            mpld3.save_html(fig, open(out_fname, 'w'))
        else:
            out_fname = os.path.join(options.outdir, 'plots', 'gene_overview_%s%s%s.%s' % (gene.name, event_tag, log_tag, options.format))
            plt.savefig(out_fname, format=options.format, bbox_inches='tight')
        plt.close(fig)
github kennethreitz / coinbin.org / predictions.py View on Github external
# log-transform y
    df['y'] = np.log(df['y'])

    model = Prophet(weekly_seasonality=True, yearly_seasonality=True)
    model.fit(df)

    periods = PERIODS if not render else GRAPH_PERIODS

    future_data = model.make_future_dataframe(periods=periods, freq='d')
    forecast_data = model.predict(future_data)

    if render:
        matplotlib.pyplot.gcf()
        fig = model.plot(forecast_data, xlabel='Date', ylabel='log($)')
        return mpld3.fig_to_html(fig)

    forecast_data_orig = forecast_data  # make sure we save the original forecast data
    forecast_data_orig['yhat'] = np.exp(forecast_data_orig['yhat'])
    forecast_data_orig['yhat_lower'] = np.exp(forecast_data_orig['yhat_lower'])
    forecast_data_orig['yhat_upper'] = np.exp(forecast_data_orig['yhat_upper'])

    df['y_log'] = df['y']  #copy the log-transformed data to another column
    df['y'] = df['y_orig']  #copy the original data to 'y'

    # print(forecast_data_orig)
    d = forecast_data_orig['yhat'].to_dict()
    predictions = []

    for i, k in enumerate(list(d.keys())[-PERIODS:]):
        w = maya.when(f'{i+1} days from now')
        predictions.append({
github svenkreiss / databench_examples / analyses / mpld3pi / analysis.py View on Github external
[r[0] for r in rnd_draws], 50,
            normed=1, facecolor='green', alpha=0.75
        )
        self.ax2.cla()
        self.ax2.set_xlabel('r2')
        self.ax2.set_ylabel('Normalized Distribtuion')
        self.ax2.set_xlim(0, 1)
        self.ax2.set_ylim(0, 1.5)
        self.ax2.grid(True)
        self.ax2.hist(
            [r[1] for r in rnd_draws], 50,
            normed=1, facecolor='blue', alpha=0.75
        )

        # send new matplotlib plots to frontend
        self.emit('mpld3canvas', mpld3.fig_to_dict(self.fig))
github HybriD3-database / MatD3 / materials / plotting / pl_plotting.py View on Github external
# print points[0]
    labels = []
    for i,j in zip(x,y):
        label = '<div class="tooltiptext">'
        label += '{2}: {1} <br> {3}: {0}'.format(i, j, y_label, x_label)
        label += '</div>'
        labels.append(label)

    tooltip = plugins.PointHTMLTooltip(points[0], labels, hoffset=-tooltipwidth/2, voffset=-tooltipheight, css=css)

    plugins.connect(fig, tooltip)

    save_name = "{}.html".format(filename.split(".")[0])
    # filename = "{}.png".format(filename.split(".")[0])
    # plt.savefig(filename, dpi = 300, bbox_inches='tight')
    mpld3.save_html(fig, save_name)
    plt.close()
    # mpld3.fig_to_html(plt_figure)