Python Jupyter Notebook:在类的 _repr_html_() 方法中嵌入交互式绘图

2024-01-04

我试图在其中嵌入一个交互式图表_repr_html_()一个类的方法C.

到目前为止,我所尝试的方法似乎不适用于我的 Jupyter Notebook。

情节(蟒蛇)

这是一个使用示例图Plotly https://plotly.com/python/line-and-scatter/保存为 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')

和一个班级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

另一个测试使用Chart.js https://www.chartjs.org。在这种情况下,也没有运气。

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.


你应该设置脚本的 src 属性 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-src或嵌入一个而不是两者。

此外,嵌入的脚本不是有效的 Javascript。

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

在笔记本单元中独立运行的完整代码:

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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python Jupyter Notebook:在类的 _repr_html_() 方法中嵌入交互式绘图 的相关文章

随机推荐