Baekyeon Baekyeon - 2 months ago 19
HTML Question

Aligning axes in D3

I was able to render the line graph below with my drawLine function. As you can see, the x-axis tick marks don't align perfectly with the points. How can I shift the x-axis tick marks to the left so that the "10 Sep" tick is right below the y-axis?

Line Graph

Here's my code:

function drawLine(line_data) {
var vizLine = line_data;

var date_format = d3.time.format("%d %b");
var xline = d3.time.scale()
.range([0, width]);

var yline = d3.scale.linear()
.range([height, 0]);

var xAxisline = d3.svg.axis()
.scale(xline)
.orient("bottom")
.tickFormat(date_format);

var yAxisline = d3.svg.axis()
.scale(yline)
.orient("left")
.tickFormat(d3.format("d"));

var line = d3.svg.line()
.x(function(d) {
return xline(d.date2);
})
.y(function(d) {
return yline(d.books);
});

var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);

var lineGraph = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

vizLine.forEach(function(d) {
d.date = d[0];
d.books = +(d[1]);
d.date2 = Date.parse(d.date);
});

xline.domain(d3.extent(vizLine, function(d) {
return d.date2;
}));
yline.domain([0, d3.max(vizLine, function(d) {
return (d.books + 1);
})]);

lineGraph.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxisline);

lineGraph.append("path")
.datum(vizLine)
.attr("class", "line")
.attr("d", line);

lineGraph.selectAll("dot")
.data(vizLine)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) {
return xline(d.date2);
})
.attr("cy", function(d) {
return yline(d.books);
})
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div.html(d.date + "<br/>" + d.books + " books")
.style("width", 70)
.style("height", 35)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
}

Answer

Probably applying a non-zero x component to the translation of the x axis corrects your bug, but it's hard to tell without seeing the whole code.

Something like

lineGraph.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(" + margin.left + "," + height + ")")
    .call(xAxisline);