字典数据到d3线图 - Django Python 服务器端

3 投票
1 回答
2040 浏览
提问于 2025-04-18 15:19

我有一个字典对象,里面存储了日期时间和对应的数值。我已经按照以下格式设置好了我的坐标轴;

var parseDate = d3.time.format(""d %b %Y %H:%M:%S %p").parse;

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
        .range([height,0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

我现在搞不明白的是,怎么写出一个和这个等效的东西;

        var line = d3.svg.line()
        .x(function (data) { return x(data.property1); })
        .y(function (data) { return y(data.property2); });

但是要使用我在django视图中得到的字典。我是应该返回一个render_to_response,把我的数据字典传过去,然后希望data.property1能把我的x值设置成我在视图中生成的那样?还是说我应该在上面的函数中做一个ajax调用,通过HttpResponse(data)来返回数据?

我对javascript和d3还不太熟悉,但没有足够的时间去深入学习,谢谢!

1 个回答

4

你说得对,应该使用 HttpResponse()

D3.js 有一个很方便的 d3.json 方法,它可以在网址 "/myDataURL/" 发起一个 GET 请求,并把返回的数据解析成 JSON 对象:

d3.json("/myDataURL/", function(error, data) {
    // ... (Use `data` to load the visualization.)
});

这意味着你可以很轻松地将你的 dict 以 JSON 格式从 Django 发送出去:

import json
def myView(request):
    // ... Prepare the `data` dict.
    return HttpResponse(json.dumps(data), content_type="application/json")

注意:在最近的 Django 1.7 及以上版本中,使用带有内容类型的 HttpResponse 可以通过使用 JsonResponse() 来简化。


现在把这些结合起来,如果你想把数据作为线条加载到(例如)折线图中,你可以使用 (来源):

var line = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.close); });

d3.json("/myDataURL/", function(error, data) {
  data.forEach(function(d) {
    d.date = parseDate(d.date);
    d.close = +d.close;
  });

  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain(d3.extent(data, function(d) { return d.close; }));

  // ... Set up the axes. See the source above for detailed instructions.

  svg.append("path")
      .datum(data)
      .attr("class", "line")
      .attr("d", line);
});

撰写回答