Django d3.js load JSON data
我正在尝试使用d3.js制作直方图。我是javascript和JSON的新手,所以需要您的帮助。
基本上,我正在尝试在此处使用此代码:
如何使用d3制作持续时间的条形图?
此处显示的代码和代码中的数据都可以正常工作,但是如何引用JSON输出的数据?
urls.py用于我的JSON数据
1 | url(r'^api/playAround', views.playAround, name='playAround'), |
view.py
1 2 3 | def playAround(request): data = Customer.objects.annotate(month=TruncMonth('Update')).values('month').annotate(countItems=Count('id')) return JsonResponse(list(data), safe=False) |
localhost / api / playAround
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | [ { "month":"2017-10-01", "countItems": 16, }, { "month":"2018-04-01", "countItems": 1, }, { "month":"2018-10-01", "countItems": 1, }, ] |
如何更改行
1 | var data =.... |
我读取并显示了JSON数据吗?
线
1 | d3.json("{% url"playAround" %}", function(error, data) {} |
没有工作。我想我在d3.js JSON javascript
中没有重点
模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | <!DOCTYPE html> <meta charset="utf-8"> <style> .bar { fill: steelblue; } .bar:hover { fill: brown; } .axis--x path { display: none; } </style> <svg width="960" height="500"></svg> <script src="/static/js/d3.v5.min.js"> var svg = d3.select("svg"), margin = { top: 20, right: 20, bottom: 30, left: 40 }, width = +svg.attr("width") - margin.left - margin.right, height = +svg.attr("height") - margin.top - margin.bottom; var x = d3.scaleBand().rangeRound([0, width]).padding(0.1), y = d3.scaleLinear().rangeRound([height, 0]); var g = svg.append("g") .attr("transform","translate(" + margin.left +"," + margin.top +")"); var data = d3.json("{% url 'playAround' %}", function(error, data) { x.domain(data.map(function(d) { return d.month; })); y.domain([0, d3.max(data, function(d) { return d.countItems; })]); }); g.append("g") .attr("class","axis axis--x") .attr("transform","translate(0," + height +")") .call(d3.axisBottom(x)); g.append("g") .attr("class","axis axis--y") .call(d3.axisLeft(y)) .append("text") .attr("transform","rotate(-90)") .attr("y", 6) .attr("dy","0.71em") .attr("text-anchor","end") .text("Frequency"); g.selectAll(".bar") .data(data) .enter().append("rect") .attr("class","bar") .attr("x", function(d) { return x(d.month); }) .attr("y", function(d) { return y(d.countItems); }) .attr("width", x.bandwidth()) .attr("height", function(d) { return height - y(d.countItems); }); |
我找到了解决方案。与将数据包含在代码中相反,访问JSON对象时必须做一件事:
由于您没有数据的全局变量,因此必须在d3.json中包含所有域或附加信息。
所以这是相关代码:
1 2 3 4 5 | d3.json("{% url"playAround" %}", function(error, data) { ..... // insert here the x./y.domain and g.append information }); |
另外,以上代码仅适用于d3.v4.min.js。