在Jupyter Notebook中使用Chart.js会引发'未捕获引用错误:图表未定义'

uttx8gqw  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(364)

我试图在Jupyter Notebook中使用Chart.js(来解决这个issue问题),但是图表没有在Jupyter Notebook中显示出来(但是它在Google Colab中工作)。
我已经创建了一个最小的可重复示例,其方式与下面的示例类似:Python Jupyter Notebook: Embed an interactive plot in the repr_html() method of a class-单元格正在返回带有图表的HTML表示形式
但是,示例代码在Jupyter Notebook中不起作用:

class ClassTwo:
    def _repr_html_(self):

        ret = """
        <h2>Chart</h2>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

        <canvas id="myChart" style="width:100%;max-width:700px"></canvas>

        <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()

预期的输出应该是一个图表,但我在开发者控制台中得到了一个错误:

Uncaught ReferenceError: Chart is not defined
    at <anonymous>:4:11

本地Jupyter笔记本的屏幕截图

谷歌协作
上面的代码片段在Google Colab中工作。我不知道为什么它在Colab中工作,而在本地的Jupyter Notebook中不工作?
你知道为什么Chart没有定义吗?

ssm49v7z

ssm49v7z1#

我已经找到了解决的方法。出现问题是因为chartjs没有按时加载。我用requirejs修复了这个问题-包是用require加载的。下面是我的工作代码:

class ClassTwo:
    def _repr_html_(self):

        ret = """

<canvas name="chart" id="f53605da-a239-4014-873c-7c0f5282ff55" width="538" height="538"></canvas>
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
<script>
    require.config({
        paths: {
            chartjs: 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min'
        }
    });

    require(['chartjs'], function(Chart) {
        const ctx = document.getElementById('f53605da-a239-4014-873c-7c0f5282ff55').getContext('2d');

        var xyValues = [{x:50, y:7}, {x:60, y:8}, {x:70, y:8}, {x:80, y:9}, {x:90, y:9},];

          new Chart(ctx, {
            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()

相关问题