Chartjs-Use Chart.js in Jupyter Notebook throws `Uncaught ReferenceError: Chart is not defined`

1👍

I’ve figured out how to solve it. There was a problem because chartjs was not loaded on time. I fixed this with requirejs – the package is loaded with require. Here is my working code:

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

Leave a comment