我想从json feed创建一个简单的饼图,但是在按照几个例子后,我发现firebug没有给我任何错误,但是没有饼图显示。我不确定它是否与我的json结构有关?我有一段时间会收到这样的错误:
Object #<Object> has no method 'map'
以下是我的代码:
<script>
function init(){
var w = 400;
var h = 400;
var r = h/2;
var color = d3.scale.ordinal()
.range(["#98abc5","#8a89a6","#7b6888","#6b486b","#a05d56","#d0743c"]);
var sql = new cartodb.SQL({ user: 'ceigis' });
sql.execute("SELECT status, COUNT(status) FROM deldot_rail_crossing GROUP BY status")
.done(function(data) {
for (var i = 0; i < data.total_rows; i++) {
var filterdata = data.rows[i];
}
var chart = d3.select("body").selectAll("svg")
.data(filterdata)
.attr("width", w)
.attr("height", h)
.attr("transform", "translate(" + r + "," + r + ")")
var arc = d3.svg.arc()
.outerRadius(r);
var pie = d3.layout.pie()
.value(function(d) { return d.count; });
var arcs = chart.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice");
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } )
.attr("d", arc);
arcs.append("svg:text")
.attr("transform", function(d) {
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d, i) { return filterdata.rows[i].status; });
})
.error(function(errors) {
// do nothing
})
}
</script>
</head>
<body onload="init()">
</body>
</html>
以下是我的json查询返回的内容:
{"time":0.005,"fields":{"status":{"type":"string"},"count":{"type":"number"}},
"total_rows":4,"rows":[{"status":"private","count":169},{"status":"comp","count":41},
{"status":"not_comp","count":276},{"status":"pre_qaqc","count":10}]}
任何帮助将不胜感激
答案 0 :(得分:1)
您的变量filterdata
是一个对象,您应该将数组传递给data
方法。如果您使用.selectAll("svg").data([filterdata])
,则需要在enter
上附加元素:
var chart = d3.select("body").selectAll("svg")
.data([filterdata])
.enter()
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("transform", "translate(" + r + "," + r + ")");
D3期望data
的争论成为一个数组。 filterdata
对象没有map
方法,因而错误。您还可以将单个对象绑定到选择,但您需要先将其追加:
var chart = d3.select("body").append("svg")
.datum(filterdata)
.attr("width", w)
.attr("height", h)
.attr("transform", "translate(" + r + "," + r + ")");
此致