I use Flot for chart in my Django app. I want to draw every day a chart that has many data series (lines chart). Each day, the serial number could change and I don't know how to handle this with flot. My code is more or less this:
test.py
data_day_1 = [[1,56],[2,65],[3,45]]
data_day_2 = [[1,45],[2,23],[3,89]]
return render_to_response('test.html', {'data_day_1': data_day_1,
'data_day_2': data_day_2,
},
context_instance=RequestContext(request))
test.html
<div class="portlet-body">
<div id="site_statistics" class="chart"></div>
</div>
<script type="text/javascript">
var data1 = [];
{% for x, y in data_day_1 %}
data1.push([{{x}},{{y}}])
{% endfor %}
var data2 = [];
{% for x, y in data_day_2 %}
data2.push([{{x}},{{y}}])
{% endfor %}
$(function () {
var Options = { lines: {show: true},
}
$.plot($("#site_statistics"),
[{data: data1,
color: "#454d7d",
points: {show: true},
label: "data_day_1",
},
{data: data2,
color: "#454d7d",
points: {show: true},
label: "data_day_2",
}
],Options);
});
Another day I might have another set (eg data_day_3) and do not know how to do. How can I do to manage the transfer of data and the design of the new line dynamically? Thanks for your help.
You can encode your data in json:
from django.utils import simplejson as json
data_all_days = [
{'label': 'Day 1',
'data': [[1, 4], [1,8], [9, 8]],
'color': '#000',
},
{'label': 'Day 2',
'data':...,
'color': ...,
},
...]
render_to_response( ... {'charts': json.dumps(data_all_days)})
and in the template just use the json as javascript code:
var chart_data = {{ charts|safe }};
$.plot($('#site_statistics'), chart_data);
You'll have the structure of data_all_days
in your js code and will parse it with a cycle. Read on jquery.each .
While running this code, open it in Chrome or FireFox and open developer tools (Ctrl+I or F12) and see the debug console, it will show if there are errors in the JavaScript.
|safe
is a template filter to prevent code from being html-quoted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.