我希望如果数据与美国不同,d.pais
! = "USA" 数据被省略。我希望数据与美国不同,d.pais!="美国",数据被省略。并且没有创建圆圈。
我该怎么做?
d3.selectAll("circle").remove();
g.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", function(d) {
if(d.pais=="USA" ){
return projection([d.longitud, d.latitud])[0];
}
})
.attr("cy", function(d) {
if(d.pais=="USA" ){
return projection([d.longitud, d.latitud])[1];
}
})
.attr("r", function(d) {
if(d.pais=="USA" ){
return 3;
}
})
在 D3 逻辑中使用数据数组之前,筛选数据数组要容易得多:
var usaData = data.filter(d => d.pais === "USA");
g.selectAll("circle")
.data(usaData)
.enter()
.append("circle")
...
您可以在 W3 学校网站上了解有关所有数组操作函数的更多信息...
在你的方案中,你的意思是你想要根据你的数据">筛选"元素。
您可以对代码中的不同步骤进行过滤。就像@SteveR的答案一样,您可以使用javascript数组方法将数据预处理到d3代码中。
或者在 d3.js 中,它还提供了一些进行过滤的方法:
-
在数组文档中
筛选 d3.array,继承到javascript。数组和更多扩展到统计方法 -
在元素文档中
过滤 A. 使用 d3.selection.filter
b. 使用 d3.select()
第一部分
这部分就像@SteveR的回答
const filtered = data.filter((d)=>{return d.location !== 'USA';})
第二部分
这部分是对元素进行过滤(使用这种方法,您将不得不处理更多考虑)
使用 d3.selection.filter 方法
const svg = d3.select(DOM.svg(200,200));
const circles = svg.selectAll('circle').data(data);
const circlestages = svg.selectAll('text')
.data(data)
circles.enter()
.append('circle')
.attr('cx', 10)
.attr('cy', (d,i)=> 10 + i*20)
.attr('r', 5)
.attr('fill', 'red');
circlestages.enter()
.append('text')
.attr('x', 15)
.attr('y', (d,i)=> 12 + i*20)
.attr('font-size',10)
.text((d,i)=>{
return "name: "+ d.name +" , "+"location: " + d.location ;
});
// filter after the element created
svg.selectAll('circle').filter((d,i)=> d.location === 'USA').remove();
svg.selectAll('text').filter((d,i)=> d.location === 'USA').remove();
使用 d3.select 过滤元素并删除
const svg = d3.select(DOM.svg(200,200));
const circles = svg.selectAll('circle').data(data);
const circlestages = svg.selectAll('text')
.data(data);
circles.enter()
.append('circle')
.attr('cx', 10)
.attr('cy', (d,i)=> 10 + i*20)
.attr('r', 5)
.attr('fill', 'red');
circlestages.enter()
.append('text')
.attr('x', 15)
.attr('y', (d,i)=> 12 + i*20)
.attr('font-size',10)
.text((d,i)=>{
return "name: "+ d.name +" , "+"location: " + d.location ;
})
// filter the element using d3.select()
svg.selectAll('text').select((d,i,g)=> {return d.location === 'USA'?g[i]:null}).remove();
svg.selectAll('circle').select((d,i,g)=> {return d.location === 'USA'?g[i]:null}).remove();
天文台演示:https://beta.observablehq.com/@weitinglin/how-can-i-skip-an-element-of-an-array-when-i-perform-a-data-data-