Search code examples
javascriptd3.jsstacked-area-chart

How to select data


I have below code to display chart

        d3.json("dat.csv", function(error, data) {


        Data.forEach(function(d) {

            d.Data = parseDate(d.Data);
            d.Free = +d.Free;

        });

This is picking data form all hosts , I want to restrict it to pick data. field will have all host names. how to put a check the data? please help


Solution

  • You can filter your data after receiving the d3.json response. I created a new variable (host1Data) for clarity:

    d3.json("dat.json", function(error, data) {
    
        var host1Data = data.filter(function(d){
                            return d.host.name === 'host1';
                        });
    
        host1Data.forEach(function(d) {
    
            d.Date.Time = parseDate(d.Date.Time);
            d.CPU.Free = +d.CPU.Free;
    
        });
    
        // Use host1Data instead of data in the rest of your code
    });
    

    Alternatively, you can also filter the data when passing it to svg using javascript's filter function:

    var mychart = svg.selectAll(".mychart")
      .data(data.filter(function(d){return d.host.name === 'host1'})
    .enter().append("g")
      .attr("class", "mychart");
    

    Or using d3's filter function:

    var mychart = svg.selectAll(".mychart")
      .data(data)
    .enter().append("g")
      .filter(function(d){return d.host.name === 'host1'}
      .attr("class", "mychart");