Published
Edited
Mar 3, 2018
2 stars
Insert cell
Insert cell
Insert cell
data=[{"name":"A","location":"USA"},
{"name":"B","location":"USA"},
{"name":"C","location":"Japan"},
{"name":"D","location":"China"},
{"name":"E","location":"USA"},
{"name":"F","location":"USA"},
{"name":"G","location":"Canada"},
{"name":"H","location":"Russian"}]
Insert cell
md`## Filter with Array.filter`
Insert cell
{
const svg = d3.select(DOM.svg(200,200))

// preprocess the data with Array.filter
const filtered = data.filter((d)=>{return d.location !== 'USA';})

const circles = svg.selectAll('circle').data(filtered)

const circlestages = svg.selectAll('text')
.data(filtered)


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 ;
})
return svg.node()
}
Insert cell
md`## Filtering on the d3.selection.filter`
Insert cell
{
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();
return svg.node()
}
Insert cell
md`## Filtering on the d3.selection directly`
Insert cell
{
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();

return svg.node()
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more