Example shows Python Chart rendered with date-time values fetched from database. Library supports numeric, date-time & category axis. Demo 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 = {{ datapoints|safe }};
var dataPoints = []
for(var i=0; i<data.length; i++) {
dataPoints.push({x: data[i].fields.x, y: data[i].fields.y})
}
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
exportEnabled: true,
animationEnabled: true,
title: {
text: "Site Traffic"
},
subtitles: [{
text: "Chart with DateTime Data from Database"
}],
axisY: {
title: "No. of Visits"
},
data: [{
type: "line",
xValueType: "dateTime",
xValueFormatString: "MMM YYYY",
dataPoints: dataPoints
}]
});
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
from datetime import datetime
from django.core import serializers
from .models import DataPoint
def index(request):
datapoint_query_set = DataPoint.objects.all().order_by('x')
for data in datapoint_query_set:
data.x = int(datetime.timestamp(data.x)) * 1000
datapoints = serializers.serialize('json', datapoint_query_set)
return render(request, "index.html", { "datapoints": datapoints})
In the above example, xValueType property is used to define the type of the x-values. xValueFormatString, yValueFormatString & zValueFormatString properties can be used to define the format of x, y & z-values respectively.