0

I am using d3js with data loaded from a CSV table. I put these values in a table and then want to set the color of the entries in column 10 depending on the value of column 2 and 3 (e.g., do something if the sum of the values in column 2 and 3 is positive).

I understand how to color one entry depending of its own value, but doing this depending of other values is beyond my programming skills. Can someone help me with this?

d3.select("#viz")
    .append("table")
    .style("border-collapse", "collapse")
    .style("border", "2px black solid")

    .selectAll("tr")
    .data(parsedCSV)
    .enter().append("tr")

    .selectAll("td")
    .enter().append("td")
    .style("border", "1px black solid")
    .style("padding", "2px")
    .text(function(d){return d;})
4

1 回答 1

1

如果您可以访问行数组,这是最简单的。我倾向于使用.each这种任务:

// ...snip...
.enter().append("tr")
.each(function(row) {
    // now the whole row array is in scope for all sub-elements
    d3.select(this)
      .selectAll("td")
        .data(function(d){ return d; })
      .enter().append("td")
        .style("border", "1px black solid")
        .style("padding", "2px")
        .style("background", function(d, i) {
            // get data for last sibling
            var prev = row[i - 1];
            // determine the color
            return prev == 1 ? 'yellow' :
                prev == 2 ? 'orange' :
                prev == 3 ? 'red' :
                'none';
        })
        .text(function(d){ return d; });
});

见小提琴:http: //jsfiddle.net/V9vMW/

于 2013-09-09T23:09:15.960 回答