Example shows Python Chart plotted using data from JSON source with the help of Python JSON encoder and decoder package. It also includes Django source code that you can run locally.
<!-- index.html --> {% load static %} <html> <head> <title>CanvasJS Python Charts</title> <script> window.onload = function () { var data = {{ co2_emission_data|safe }}; fossilFuelEmissionDps = []; landUsageEmissionDps = []; for(var i=0; i<data.length; i++) { fossilFuelEmissionDps.push({ label: data[i].year, y: data[i].fossilfuel }); landUsageEmissionDps.push({ label: data[i].year, y: data[i].landusechange }); } var chart = new CanvasJS.Chart("chartContainer", { theme: "light2", exportEnabled: true, title: { text: "Global CO₂ Emission" }, axisY: { title: "CO₂ Emission (In Billion Tonnes)", valueFormatString: "0,.,.,.BT", }, toolTip: { shared: true }, legend: { cursor: "pointer", itemclick: function (e) { if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) { e.dataSeries.visible = false; } else { e.dataSeries.visible = true; } e.chart.render(); } }, data: [{ type: "spline", name: "Fossil Fuel", showInLegend: true, yValueFormatString: "0,.,.,.00Billion Tonnes", dataPoints: fossilFuelEmissionDps },{ type: "spline", name: "Land Use Change", showInLegend: true, yValueFormatString: "0,.,.,.00Billion Tonnes", dataPoints: landUsageEmissionDps }] }); chart.render(); } </script> </head> <body> <div id="chartContainer" style="height: 360px; width: 100%;"></div> <script src="{% static 'canvasjs.min.js' %}"></script> </body> </html>
from django.shortcuts import render import json import os def index(request): dir_path = os.path.dirname(os.path.realpath(__file__)) data = open(dir_path + "/static/co2-emission-fuels.json").read() co2_emission_data = json.loads(data) return render(request, "index.html", { "co2_emission_data": co2_emission_data})
Setting showInLegend property of Dataseries shows legend for the same. Format of axis labels can be customized by setting valueFormatString. Format of x & y-values shown in tooltip & legend can be customized by setting xValueFormatString & yValueFormatString properties.