Skip to content

Embed an interactive plot in the _repr_html_() method of a class #13644

@pietrodantuono

Description

@pietrodantuono

I am trying to embed an interactive graph in the _repr_html_() method of a class C.

What I have tried so far does not seem to be working in my Jupyter Notebook, and I think there may be many programmers that would find such a feature useful.

Plotly (python)

Here is an example plot using Plotly saved as HTML div:

import plotly.offline as opy
import plotly.io as pio
import plotly.graph_objs as go
import numpy as np

pio.templates.default = "none"

the_x = np.logspace(4,9)
data = [
    go.Scattergl(
        x=the_x,
        y=1E10*the_x **(-1),
        name="Example",
        line=dict(color="Red", width=1),
    )
]
layout = go.Layout(
    xaxis=dict(
        title="X axis",
        linecolor="#000",
        type="log",
        tickformat=".0e",
    ),
    yaxis=dict(
        title="Y axis",
        linecolor="#000",
        type="log",
        tickformat=".0f",
    ),
    font=dict(family="Serif", size=14, color="#000"),
    legend=dict(font=dict(family="Serif", size=12, color="#000")),
)
fig = go.Figure(data=data, layout=layout)
the_div = opy.plot(fig, auto_open=False, output_type='div')

and a class ClassOne using the_div:

class ClassOne:
    def _repr_html_(self):
        ret = f"""
        {the_div}
        """
        return ret

ClassOne()  # returns blank. Chrome's 'Inspect HTML' gives many errors that I am not
            # exactly able to understand, among which:
            # "Couldn't process kernel message error: Mismatched"

Chart.js

Another test using Chart.js. Also in this case, no luck.

class ClassTwo:
    def _repr_html_(self):
        ret = """
        <h2>Click the button below:</h2>
        <button type="button" onclick="youclicked()">Click Me</button>
        <script>  
        function youclicked(){  
        alert("You Clicked!");  
        }  
        </script>
        <canvas id="myChart" style="width:100%;max-width:700px"></canvas>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js">
          {{
            var bt = document.getElementById("clearBtn");
            bt.onclick = function(){{ alert('hi'); }};;
          }}        
        </script>
        <script>
          var xyValues = [
            {x:50, y:7},
            {x:60, y:8},
            {x:70, y:8},
            {x:80, y:9},
            {x:90, y:9},
          ];

          new Chart("myChart", {
            type: "scatter",
            data: {
              datasets: [{
                pointRadius: 4,
                pointBackgroundColor: "rgb(0,0,255)",
                data: xyValues
              }]
            },
            options: {
              legend: {display: false},
              scales: {
                xAxes: [{ticks: {min: 40, max:100}}],
                yAxes: [{ticks: {min: 6, max:10}}],
              }
            }
          });
        </script>
        """
        return ret

ClassTwo()  # The button is rendered and the youclicked() function is run.
            # Unfortunately, no plots rendered. Among the HTML errors I see 
            # "Uncaught ReferenceError: Chart is not defined", but I
            # cannot correctly provide the CDN to the page.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions