简体   繁体   中英

Filter dataset for path element in D3js (v3)

I'm using a dataset to draw points and path elements with D3js. The dataset contains undefined values that I want to be filtered. I know how to filter the point elements but don't manage to filter the dataset for the path elements like area and line. I want to draw an area and line only based on the actual values, so I have to filter the undefined elements. My dataset looks like this:

ds = [
{x: 0, param1: 230, param2: 1070},
{x: 2, param1: 190, param2: undefined},
{x: 5.5, param1: 161, param2: 1207},
{x: 8, param1: 167, param2: 1165},
{x: 11, param1: 154, param2: 987},
{x: 12, param1: undefined, param2: 876},
{x: 12.32, param1: 187, param2: undefined},
{x: 15, param1: 156, param2: undefined},
....
];

I know how to filter a dataset to draw circle elements in a scatterplot (simplified version):

group.selectAll("circle")
    .data(ds)
    .enter()
    .append("circle")  
    .filter(function(d) {return d.param1 != undefined} )
    .(...);

I've tried the following code for the area:

var area = d3.svg.area()
    .x(function(d) {return x(d.x);})
    .y0(h-padding)
    .y1(function(d) {return y(d.param2);});
group.append("path")
    .attr("class","area")
    .datum(ds)
    .filter(function(d) { return d.param2 != undefined})
    .attr("d",area);

I think I'm using the filter function in an incorrect way. I've tried to add the filter to the variable declaration of the area, but I didn't work either. For the line element I got the same problem.

The SO examples that I studies are all about filtering circle/dots (eg) elements. I didn't find anything about filtering path elements.

Any help is appreciated..

It's much easier to do the filtering before you bind the data to the DOM, rather than trying to transform it after you've drawn elements, etc. You can use a standard array filter to remove the undefined data points from your data set:

array.filter( function(d){ // your filter code here } )

In context:

group.selectAll("circle")
    .data( ds.filter(function(d) {return d.param1 != undefined}) )
    .enter()
    .append("circle")  

The same principle applies for the area plot:

group.append("path")
    .attr("class","area")
    .datum( ds.filter(function(d){ return d.param2 != undefined }) )
    .attr("d",area);

Data is much easier to manipulate before it is bound to the DOM, so do as much cleaning and filtering as you can beforehand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM