Life as Clay

Archive for the ‘d3’ Category

Nested arrays in d3.js

leave a comment »

I find nested arrays to be difficult to work with in d3.js. Every time I begin a new d3 project, I spend a few minutes confused about how to access the data. I built this small file to be able to play with the values and remind myself what they do.

<!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
  font: 14px sans-serif;
  font-weight: bold;
}

 .chart {
    background-color: #efefef;
    shape-rendering: crispEdges;
 }

 .series {
    background-color: red;
 }

 .text0 {
    fill: red;
 }

 .text1 {
    fill: green;
 }

 .text2 {
    fill:steelblue;
 }

 .text3 {
    fill: yellow;
 }

 .text4 {
    fill: purple;
 }

 .text5 {
    fill:brown;
 }

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>


<script type="text/javascript">
var nestedArray = [[5, 10, 15, 20, 25],
                   [10, 20, 30, 40, 50],
                   [43, 34, 17, 9, 2]];


var chart = d3.select("body").append("svg")
            .attr("class", "chart")
            .attr("id", "chart")
            .attr("width", 550)
            .attr("height", 40 * 5);

var series = chart.selectAll(".series")
                .data(nestedArray)
                .enter().append("svg:g")
                .attr("class", "series");

var point  = series.selectAll(".point")
             .data(         function(d,i,j) { return d;          } )
             .enter().append("text")
             .text(         function(d,i,j) { return d;          } )
             .attr("class", function(d,i,j) { return "text" + j; } )
             .attr("x",     function(d,i,j) { return 10 * d;     } )
             .attr("y",     function(d,i,j) { return 40 * (j+1); } );

</script>
</body>
</html>

Written by Clay

September 15, 2013 at 17:16

Posted in Code, d3, javascript

Tagged with