Example shows Python Dynamic Line Chart that adds new datapoint to chart every 1 second. They are also referred to as Live Data Streaming Charts. Demo also includes Django source-code that you can try running locally.
<!-- index.html --> {% load static %} <html> <head> <title>CanvasJS Python Charts</title> <script> window.onload = function () { // Initial Values var xValue = 0; var yValue = 10; var newDataCount = 6; dataPoints = []; var chart = new CanvasJS.Chart("chartContainer", { exportEnabled: true, title: { text: "Dynamic Line Chart from JSON API" }, data: [{ type: "line", dataPoints: dataPoints }] }); updateData(); function addData(data) { if (newDataCount !== 1) { $.each(data, function (key, value) { dataPoints.push({ x: value.x, y: parseFloat(value.y) }); xValue++; yValue = parseFloat(value.y); }); newDataCount = 1; } else { dataPoints.shift(); dataPoints.push({ x: data[0].x, y: parseFloat(data[0].y) }); xValue++; yValue = parseFloat(data[0].y); } chart.render(); setTimeout(updateData, 1000); } function updateData() { $.getJSON("get_datapoints?xstart=" + xValue + "&ystart=" + yValue + "&length=" + newDataCount, addData); } } </script> </head> <body> <div id="chartContainer" style="height: 360px; width: 100%;"></div> <script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script> <script src="{% static 'canvasjs.min.js' %}"></script> </body> </html>
from django.shortcuts import render from django.http import HttpResponse import random import json def index(request): return render(request, "index.html") def get_datapoints(request): default_query_params = { "xstart": 0, "ystart": 0, "length": 1 } query_params = { **default_query_params, **request.GET.dict() }; y = int(query_params["ystart"]); datapoints = [] for i in range(int(query_params["length"])): y += round(5 + random.random() * (-5-5)) datapoints.append({ "x": (int(query_params["xstart"]) + i), "y": y}) return HttpResponse(json.dumps(datapoints), content_type="application/json")
You can update any chart element dynamically by modifying chart-options & calling render method. You can even use set method to update existing value of a property. addTo method can be used to add new datapoint to the chart.