简体   繁体   中英

Python Jupyter Notebook: Embed an interactive plot in the _repr_html_() method of a class

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.

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>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
        <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>
          {{
            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.

You should either set src attribute of the script or embed one not both.

Also, the embedded script isn't valid Javascript.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>

Full code running standalone in notebook cell:

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">
          alert('hello');       
        </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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM