Learning D3 Part 5: Axes
In Learning D3 Part 4, I briefly introduced SVG, the differences between SVG and Canvas, and drew a chart grid to illustrate how SVG’s canvas goes from top/left to bottom/right.
D3 has a nice axis component for drawing reference lines, tick marks, and labels, which cleans up some of the code from the previous example. Here’s another good tutorial on it. Here’s the previous example, now drawn using d3.axis.
This example also contains tick marks as part of the axis lines. Might be unnecessary chart-junk depending on the situation, but they’re easily removed if you don’t need them.
Code:
// Define identity (1:1) scales var x = d3.scale.identity().domain([0,450]); var y = d3.scale.identity().domain([0,300]); // Define container var chart = d3.select("body") .append("svg") .attr("class", "chart") .attr("width", 490) .attr("height", 330) .append("g") // move 0,0 slightly down and right to accomodate axes .attr("transform", "translate(30,20)"); // Draw X-axis grid lines chart.selectAll("line.x") .data(x.ticks(10)) .enter().append("line") .attr("class", "x") .attr("x1", x) .attr("x2", x) .attr("y1", 0) .attr("y2", 300) .style("stroke", "#ccc"); // Draw Y-axis grid lines chart.selectAll("line.y") .data(y.ticks(10)) .enter().append("line") .attr("class", "y") .attr("x1", 0) .attr("x2", 450) .attr("y1", y) .attr("y2", y) .style("stroke", "#ccc"); // Define stock x and y axis var xAxis = d3.svg.axis().scale(x).orient('top'); var yAxis = d3.svg.axis().scale(y).orient('left'); chart.append('g') .attr("class", "axis") .call(xAxis); chart.append('g') .attr("class", "axis") .call(yAxis); |
Still not much to see yet, but I’m establishing the foundation on which to build.
