在d3中过滤数据以绘制圆形或正方形 [英] Filter data in d3 to draw either circle or square
问题描述
我有一点麻烦理解d3中的选择和过滤。假设我有一个简单的数组:
data = [1,2,6,3,4]
我想画圆,如果值<我的代码现在只画出圆形,看起来像这样:
var svg = d3。 select(body)append(svg)
svg.selectAll(shapes)
.data(data)
.enter()
.append圈子)
和其他属性。我需要使用 .filter()
方法,但我不知道放在哪里。我尝试做类似的事情:
var svg = d3.select(body)append(svg)
svg.selectAll(shapes)
.data(data)
.enter()
.filter(function(d){if(d> 5){console.log 'working');})
.append(circle)
使用 append
方法获取错误。
问题是,在你 .enter()
您返回一个嵌套数组,因此您的错误:
未捕获TypeError: Object [object Array]没有方法'append'
使用 .filter $ c>,您需要在
.append()
后应用 :
var data = d3.range(10);
var svg = d3.select(body)。append(svg);
var shapes = svg.selectAll(。shapes)
.data(data).enter();
shapes.append(circle)
.filter(function(d){return d< 5;})
.attr(cx,function ,i){return(i + 1)* 25;})
.attr(cy,10)
.attr(r,10)
shapes.append(rect)
.filter(function(d){return d> = 5;})
.attr(x,function d,i){return(i + 1)* 25;})
.attr(y,25)
.attr(width,10)
.attr高度,10);
使用上述代码(也在,例如
var shapes = svg.selectAll(。shapes)
.data(data.filter ){return d< 5;}))。enter()
.append(circle)
.attr(cx * 25;})
.attr(cy,10)
.attr(r,10)
I'm having a bit of trouble understand selections and filtering in d3. Let's say I have a simple array:
data = [1, 2, 6, 3, 4]
I want to draw circles if the value < 5 and squares if it's >= 5. My code right now only draws circles and looks like this:
var svg = d3.select("body").append("svg")
svg.selectAll("shapes")
.data(data)
.enter()
.append("circle")
and other attributes for circles. I need to use the .filter()
method, but I don't know where to put it. I tried doing something like:
var svg = d3.select("body").append("svg")
svg.selectAll("shapes")
.data(data)
.enter()
.filter(function(d){if (d>5){console.log('working');})
.append("circle")
but then I get an error with the append
method. Can someone point me in the right direction on how I'd accomplish this?
The problem is that after you .enter()
you are returning a nested array, hence your error:
Uncaught TypeError: Object [object Array] has no method 'append'
To use .filter()
, you need to apply it after the .append()
:
var data = d3.range(10);
var svg = d3.select("body").append("svg");
var shapes = svg.selectAll(".shapes")
.data(data).enter();
shapes.append("circle")
.filter(function(d){ return d < 5; })
.attr("cx", function(d, i){ return (i+1) * 25; })
.attr("cy", 10)
.attr("r", 10);
shapes.append("rect")
.filter(function(d){ return d >= 5; })
.attr("x", function(d, i){ return (i+1) * 25; })
.attr("y", 25)
.attr("width", 10)
.attr("height", 10);
Using the code above (also in this fiddle), I get the following output:
Note that you can also achieve the same effect using Array's filter method, e.g.
var shapes = svg.selectAll(".shapes")
.data(data.filter(function(d){ return d < 5; })).enter()
.append("circle")
.attr("cx", function(d, i){ return (i+1) * 25; })
.attr("cy", 10)
.attr("r", 10);
这篇关于在d3中过滤数据以绘制圆形或正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!