0

我在我的 Django 应用程序中使用 Flot 作为图表。我想每天绘制一个包含许多数据系列的图表(折线图)。每天,序列号都可能发生变化,我不知道如何用 flot 处理这个问题。我的代码或多或少是这样的:

测试.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))       

测试.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);
});     

改天我可能有另一组(例如data_day_3)并且不知道该怎么做。如何动态管理数据传输和新线路的设计?谢谢你的帮助。

4

1 回答 1

1

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.

于 2013-07-10T21:28:53.720 回答