Skip to content

Instantly share code, notes, and snippets.

@eesur
Last active August 29, 2015 13:58
Show Gist options
  • Save eesur/9937740 to your computer and use it in GitHub Desktop.
Save eesur/9937740 to your computer and use it in GitHub Desktop.
d3 | table data from matrix

Aim

Create and populate a html table form an array within an array (matrix)

Info and sources

Based on Nested Selections

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Making a table from matrix</title> <!-- based on http://bost.ocks.org/mike/nest/ -->
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
body {font-family: monospace; line-height: 160%; font-size: 18px; margin: 0;}
table {
border-collapse: collapse;
border-spacing: 0;
}
th, td {
padding: 1rem;
text-align: right;
border: 1px dotted #ccc;
}
</style>
</head>
<body>
<script>
var matrix = [
[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
];
// selecting the body
var body = d3.select("body");
// append a table element to the body
var table = body.append("table");
// append entering rows to the table via data-join (Since selectAll is called on the selected table element, it establishes a new parent node of table instead of the default html)
var tr = table.selectAll("tr")
.data(matrix)
.enter()
.append("tr");
// append entering cells to each row
var td = tr.selectAll("td")
.data(function(d) { return d; })
.enter()
.append("td");
// add content from the dataset
var content = td.text(function(d) { return d; });
// manipulate colour of specific cells and rows: j is row ,and i is column
td.style("color", function(d, i, j) { return (j<2 && i<2 ) ? null : "red"; });
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment