Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Chart.js line chart to Jinja2/Flask html page from JS file

I have the following code in a simple Bootstrap html file which displays a Chart.js line chart.

    <div class="card-block chartjs">
       <canvas id="line-chart" height="500"></canvas>
    </div>

The js file that contains the chart's setup looks like this:

$(window).on("load", function(){

    var ctx = $("#line-chart");

    var chartOptions = {
        responsive: true,
        maintainAspectRatio: false,
        legend: {
            position: 'bottom',
        },
        hover: {
            mode: 'label'
        },
        scales: {
            xAxes: [{
                display: true,
                gridLines: {
                    color: "#f3f3f3",
                    drawTicks: false,
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Month'
                }
            }],
            yAxes: [{
                display: true,
                gridLines: {
                    color: "#f3f3f3",
                    drawTicks: false,
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Value'
                }
            }]
        },
        title: {
            display: true,
            text: 'Chart.js Line Chart - Legend'
        }
    };

    var chartData = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
            label: "My First dataset",
            data: [65, 59, 80, 81, 56, 55, 40],
            fill: false,
            borderDash: [5, 5],
            borderColor: "#9C27B0",
            pointBorderColor: "#9C27B0",
            pointBackgroundColor: "#FFF",
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            pointRadius: 4,
        }, {
            label: "My Second dataset",
            data: [28, 48, 40, 19, 86, 27, 90],
            fill: false,
            borderDash: [5, 5],
            borderColor: "#00A5A8",
            pointBorderColor: "#00A5A8",
            pointBackgroundColor: "#FFF",
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            pointRadius: 4,
        }, {
            label: "My Third dataset - No bezier",
            data: [45, 25, 16, 36, 67, 18, 76],
            lineTension: 0,
            fill: false,
            borderColor: "#FF7D4D",
            pointBorderColor: "#FF7D4D",
            pointBackgroundColor: "#FFF",
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            pointRadius: 4,
        }]
    };

    var config = {
        type: 'line',

        options : chartOptions,

        data : chartData
    };

    var lineChart = new Chart(ctx, config);
});

I would like to avoid using a separated javascript file and rather just have everything in my Jinja2/Flask html page. A working example can be found in this tutorial, this is the same way that I would like to follow. I have tried to copy any paste the js part to my html page and put between <script> tags, but unfortunately it doesn't work.

Here is how I tried:

# in my jinja2/flask html page
<div class="card-body collapse in">
    <div class="card-block chartjs">
        <canvas id="line-chart" height="500"></canvas>
    </div>
</div>
<script>
    var ctx = $("#line-chart");
    var chartOptions = {
        responsive: true,
        maintainAspectRatio: false,
        legend: {
            position: 'bottom',
        },
        hover: {
            mode: 'label'
        },
        scales: {
            xAxes: [{
                display: true,
                gridLines: {
                    color: "#f3f3f3",
                    drawTicks: false,
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Month'
                }
            }],
            yAxes: [{
                display: true,
                gridLines: {
                    color: "#f3f3f3",
                    drawTicks: false,
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Value'
                }
            }]
        },
        title: {
            display: true,
            text: 'Chart.js Line Chart - Legend'
        }
    };

    // Chart Data
    var chartData = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
            label: "My First dataset",
            data: [65, 59, 80, 81, 56, 55, 40],
            fill: false,
            borderDash: [5, 5],
            borderColor: "#9C27B0",
            pointBorderColor: "#9C27B0",
            pointBackgroundColor: "#FFF",
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            pointRadius: 4,
        }, {
            label: "My Second dataset",
            data: [28, 48, 40, 19, 86, 27, 90],
            fill: false,
            borderDash: [5, 5],
            borderColor: "#00A5A8",
            pointBorderColor: "#00A5A8",
            pointBackgroundColor: "#FFF",
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            pointRadius: 4,
        }, {
            label: "My Third dataset - No bezier",
            data: [45, 25, 16, 36, 67, 18, 76],
            lineTension: 0,
            fill: false,
            borderColor: "#FF7D4D",
            pointBorderColor: "#FF7D4D",
            pointBackgroundColor: "#FFF",
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            pointRadius: 4,
        }]
    };

    var config = {
        type: 'line',

        // Chart Options
        options : chartOptions,

        data : chartData
    };

    // Create the chart
    var lineChart = new Chart(ctx, config);
});
</script>

Unfortunately I'm not so familiar with JS and don't have more ideas about what should I do to display the chart in my Flask app. What do I need to implement to make it work?

like image 922
rihe Avatar asked Aug 09 '17 12:08

rihe


2 Answers

First make sure the required JS is referenced in your template (or the template it extends).

Assuming you serve it from static/js folder:

<head>
    ...
    <script src='/static/js/Chart.bundle.min.js'></script>
    ...
</head>

Your script tag content looks mostly fine, just a little modification getting the context, and you appear to have a trailing }); that you need to remove:

<script>
    // get context
    var ctx = document.getElementById("line-chart").getContext("2d");

    ....

    // Create the chart
    var lineChart = new Chart(ctx, config);

    // REMOVE THIS FROM THE END OF YOUR SCRIPT
    //});
</script>
like image 59
bgse Avatar answered Sep 28 '22 08:09

bgse


As bgse said in his answer you need to load library first. I suggest you use CDN as that way you don't need to download ChartJS library.

Secondly, you're writing some JS that may be executed before library is fetched to the page. So what would I add is:

<div class="card-body collapse in">
    <div class="card-block chartjs">
        <canvas id="line-chart" height="500"></canvas>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script>
    $(document).ready(function(){
        // Your JS code here
        // ...
    });
</script>

This way script code will execute when all JS is loaded.

like image 26
PerunSS Avatar answered Sep 28 '22 07:09

PerunSS