Table

d3_table.html ● d3.min.js ● data/fruit_2.csv

Table

If we want to create dynamic tables with d3, we just make use of the HTML-tables. A basic HTML-table looks like this:

Fruit Size
Orange 10 cm
Apple 8 cm

Here we make use of six different HTML-Tags: table announces, that now a table will follow. thead) and (tbody) seperate the table in header and body areas. With tr we define a line of the table. Within this line-tag, we need the td -tag to define cells (columns). And then there is also a special Tag for the header-cells: th.

Example

Now lets get to this example: First we add the table -tag to the div with the id "selection":

let table = d3.select('#selection').append('table')

Then we create an array with the names of the columns, add the header-tag to it (thead), add a row (tr) to the table and insert a header cell (th) for each array entry:

table.append("thead").append("tr")
.selectAll("th")
.data(headers)
.enter().append("th")
.text(function(d) {
return d;
})

After we have created the header-cells, we first define, that this will be the table-body (tbody), and then add one line for each data element. This is then saved in the line-variable:

let line = table.append("tbody")
.selectAll("tr")
.data(data)
.enter()
.append("tr")

To this line we then append for every cell a new td (cell) and define what should be displayed in it:

line.append("td") //Name Cell
.text(d => d.name)
line.append("td") //Size Cell
.text(d => d.size + " cm")
line.append("td") //Weight Cell
.text(d => d.weight + " g")
let color = line.append("td") //Color Cell
let pricePerKg = line.append("td") //Price Cell

To create the circles and the rectangles take a look at the code on the bottom. We always first have to define an SVG and then print the shapes inside.

More about Tables