D3 Shift Ticks To Align With Axis
I'm trying to create a d3 line chart that displays monthly data. The chart draws but the ticks on the x-axis are shifted and don't align with the data points drawn. As you can see
Solution 1:
There are 2 ways to fix your issue.
Hard code and set some padding for your line and circles so they align with your
x
axis.// define the linevar valueline = d3.line().x(function(d) { returnx(d.month) + 38; //set x padding of 38 }) .y(function(d) { returny(d.average); }); svg.selectAll("dot") .data(data) .enter().append("circle") .attr("r", 5) .attr("cx", function(d) { returnx(d.month) + 38; }) .attr("cy", function(d) { returny(d.average); });
JSFiddle - https://jsfiddle.net/L5dctwsz/
- Use
d3.scaleTime
since you're dealing with month names which will solve the issue.
Set it like the following:
var x = d3.scaleTime().range([0, width]);
Parse the month and then set the domain:
// parse the date / time var parseMonth = d3.timeParse("%B");
data.forEach(function(d) {
d.month = parseMonth(d.month);
});
x.domain(d3.extent(data, function(d) {
return d.month;
}));
JSFiddle - https://jsfiddle.net/pm7gLn2u/
Post a Comment for "D3 Shift Ticks To Align With Axis"