我有一个日期、时间和价值的字典对象。我已经相应地以下列格式设置了我的轴;
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 noob,但没有足够的时间来学习,在足够的细节,谢谢!
发布于 2014-07-30 12:02:46
你说得对,你应该使用HttpResponse()**.**
D3.js有一个漂亮的d3.json方法,它将在URL "/myDataURL/“处执行GET请求,并将响应解析为JSON对象:
d3.json("/myDataURL/", function(error, data) {
// ... (Use `data` to load the visualization.)
});这意味着您可以轻松地从Django发送JSON格式的dict:
import json
def myView(request):
// ... Prepare the `data` dict.
return HttpResponse(json.dumps(data), content_type="application/json")注意:使用HttpResponse和content_type可以在最近的Django 1.7+中通过使用https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects简化
现在将所有的数据放在一起--,如果您希望实际将数据作为行加载到(例如)线图中,则可以使用(来源):
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);
});https://stackoverflow.com/questions/25036054
复制相似问题