简体   繁体   English

Django jQuery Flot Chart多个系列

[英]Django jquery flot chart multiple series

I use Flot for chart in my Django app. 我在Django应用程序中将Flot用于图表。 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 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 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. 有一天,我可能会有另一组设置(例如data_day_3),却不知道该怎么做。 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: 您可以将数据编码为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: 并在模板中只需使用json作为javascript代码即可:

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. 您将在js代码中具有data_all_days的结构, data_all_days使用一个循环对其进行解析。 Read on jquery.each . 阅读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. 在运行此代码时,请在Chrome或FireFox中将其打开,然后打开开发人员工具(Ctrl + I或F12),然后查看调试控制台,它将显示JavaScript中是否有错误。

|safe is a template filter to prevent code from being html-quoted. |safe是一个模板过滤器,用于防止代码被html引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM