Use d3.js to display a table from csv

I have been working on visualization of data analytics. One of the outputs of the process is a CSV file that I want to display on a web page. I found that the documentation for the javascript package d3.js is a bit scattered. There’s a bit here and a bit there. I pieced the sources together to produce the following code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3 Test</title>
        <script type="text/javascript" src="d3/d3.v3.min.js"></script>
        <style type="text/css">
            table {
                border-collapse: collapse;
                border: 2px black solid;
                font: 12px sans-serif;
            }
            td {
                border: 1px black solid;
                padding: 5px;
                width: 50px;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <script type="text/javascript">
            d3.text("onboarding.csv", function(data) {
                var parsedCSV = d3.csv.parseRows(data);

                var container = d3.select("body")
                    .append("table")

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

                    .selectAll("td")
                        .data(function(d) { return d; }).enter()
                        .append("td")
                        .text(function(d) { return d; });
            });
        </script>
    </body>
</html>

Notice that the format of the csv data is not critical. The code just reads in the csv by row, and then creates an HTML tabe row for each line. The end result looks something like this:

Screen Shot 2015-08-07 at 2.47.30 PM

I have barely scratched the surface of what can be done with d3.js.

Advertisements