December 31, 2012

Super simple D3 line with axis

Following last week's post, I continued looking at D3 and this time we're adding an axis, very simple again, just to get things started ... here goes again:

<html>
<head>
<meta charset="UTF-8">
<title>super simple d3 line with axis</title>
<style>
.line {
 fill: none;
 stroke: #00F;
 stroke-width: 2px;
}
.axis path,
.axis line {
   fill: none;
   stroke: black;
   shape-rendering: crispEdges;
}

.axis text {
   font-family: sans-serif;
   font-size: 10px;
}
</style>
</head>
<body>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/d3.v3.min.js"></script>
<script>

var data = [0,2,4,6,8,10,8,6,4,2,4,6,8,6,4,6,6,6,6],
width = 400,
   height = 200,
   padding = 20,
x = d3.scale.linear().domain([0, data.length]).range([padding, padding+width]),
   y = d3.scale.linear().domain([0, d3.max(data)]).range([padding+height,padding]);

/*
 add a visualisation,
 select the body tag,
 join the data array to to the body tag for our next data driven moves,
 append an svg container tag,
 give it the right width,
 give it the right height as well,
*/
var visualisation = d3
.select("body")
.data([data])
.append("svg")
.attr("height",height+(padding*2))
.attr("width",width+(padding*2));

/*
this is the line to put on the graph
append a path tag as a child of the svg tag we added to the body tag,
apply css style to make the line blue
*/
visualisation
.append("path")
   .attr("class", "line")
   .attr("d",
    d3.svg.line()
    .x(function(d,i) {return x(i);})
    .y(function(d) {return y(d);})
    );
    /*
    this is the line to represent an axis:
    - it is drawn in an SVG g tag
    - set the class to "axis" for that g tag
    - translate the coordinates down to the bottom of the graph
    - call a D3 axis function scaled to the right domain and range with 5 ticks
    */
visualisation
.append("g")
.attr("class","axis")
.attr("transform", "translate(0," + (height+padding) + ")")
.call(
d3
.svg
.axis()
.scale(x)
.orient("bottom")
.ticks(5)
);
</script>
</body>
</html>


You get:

I found that Scott Murray's tutorial was really well done. Check it out: http://alignedleft.com/tutorials/d3/axes/

No comments:

Post a Comment