Adding and using axes
Once you’ve mastered scales, you’re ready for axes.
As long as you’re following the margin convention this is going to be super easy. It takes three-ish steps:
- Create a scale (you’re doing this anyway)
- Create the axis, passing it your scale
- Append a
g
element to hold your axis, then usecall
to attach the axis to thatg
.
See the example below!
...
var datapoints = [
{ ducks: 20, geese: 30 },
{ ducks: 11, geese: 16 },
{ ducks: 125, geese: 185 },
{ ducks: 70, geese: 87 },
{ ducks: 33, geese: 34 },
{ ducks: 97, geese: 130 }
];
// STEP ONE (x and y): Create your scales
// Our data look roughly the same so we'll do 0-200 for both
var xPositionScale = d3.scaleLinear().domain([0, 200]).range([0, width]);
var yPositionScale = d3.scaleLinear().domain([0, 200]).range([height, 0]);
...
svg.selectAll("circle")
.data(datapoints)
.enter()
.append("circle")
.attr("cy", 25)
.attr("r", 3)
.attr("cx", function(d) {
return xPositionScale(d.ducks);
})
.attr("cy", function(d) {
return yPositionScale(d.geese);
});
// STEP TWO (x): Create your x axis, sending it your x axis scale
// This one is an d3.axisBottom because we want it on the bottom
var xAxis = d3.axisBottom(xPositionScale)
// STEP THREE (x): Add a g, then use .call to attach the x axis
// We use transform/translate to push it to the bottom of the page
svg.append("g")
.attr("class", "axis x-axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// STEP TWO (y): Create your y axis, sending it your y axis scale
// This one is an d3.axisLeft because we want it on the left
var yAxis = d3.axisLeft(yPositionScale);
// STEP THREE (y): Add a g, then use .call to attach the x axis
svg.append("g")
.attr("class", "axis y-axis")
.call(yAxis);