In d3 for javascript, how do you create different elements for your data?

For example, in html <table>a <tr>may contain <th>and <td>. How would you bind data to a row selection that could create even columns as <th>well as odd columns like <td>?

+5
source share
4 answers

Thus, this does not seem to be ideal either, but there is always an html () method.

var d = [['a','b','c','d']];

var r = d3.select('#myTable').selectAll('tr')
    .data(d);

r.enter().append('tr').html(function(d) {
    var i, s = '';
    for (i = 0; i < d.length; i += 1) {
        s += (i%2===0) ? '<th>' : '<td>';
        s += d[i];
        s += (i%2===0) ? '</th>' : '</td>';
    }
    return s;
}​​​​​​​​​​​​​​​);
+2
source

As far as I can tell, you're right - there is no way to do this within the standard D3 idiom. Presumably, this will be possible as soon as it selection.append()can take the function:

a choice. Append (name)

... , .

, (data, index) . , .enter() - .enter() .append, .insert .select, .

, , .enter(), : http://jsfiddle.net/xuJ6w/4/

// munge data
var tuples = data.map(function(row) {
    var newRow = [],
        x;
    // create array of objects
    for (x=0; x<row.length; x+=2) {
        newRow.push({
            label: row[x],
            value: row[x+1]               
        })
    }
    return newRow;
});

var rows = d3.select('table').selectAll('tr')
    .data(tuples);

rows.enter().append('tr');

var cellPairs = rows.selectAll('.cell')
    .data(function(d) { return d; });

var entry = cellPairs.enter();
entry.append('th')
    .attr('class', 'cell')
    .text(function(d) {
        return d.label;
    });
entry.insert('td', 'th + th')
    .attr('class', 'cell')
    .text(function(d) {
        return d.value;
    });

, :

cellPairs
    .style('background', '#CCC');

, .

+1

, , - <td> <th>, :

var d = ['a','b','c','d','e','f','g'];

var tr = d3.select("#myTableRow").selectAll("td")
    .data(d).enter().append("td")
    .text(function(d) { return d; })
    .classed("thLike", function(d,i) { return i%2===0; });

CSS

.thLike {
    font-weight: bold;
}
0

https://github.com/mbostock/d3/wiki/Selections#wiki-data

Selectors can also be intersected (".this.that" for a logical AND) or combined (".this, .that" for a logical OR).

So, something like this might work for you. I have not tested it yet (if this selection does not work, you can simply add the same class to each of the TD / TH cells and select it with TR .myClass):

var cells = tableRow.selectAll("TD, TH").data(data);
cells.enter().each(d, i) {
    var cell = d3.select(this);
    cell.append(i%2 ? "TD" : "TH");
})
0
source

All Articles