我能够使用drawLine函数渲染下面的折线图。如您所见,x轴刻度标记与点不完全对齐。如何将x轴刻度线向左移动,使“9 Sep”刻度位于y轴的正下方?
这是我的代码:
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);
});
}
答案 0 :(得分:1)
可能在x轴的平移上应用非零x分量可以纠正你的错误,但是如果不看完整个代码就很难分辨。
像
这样的东西lineGraph.append("g")
.attr("class", "x axis")
.attr("transform", "translate(" + margin.left + "," + height + ")")
.call(xAxisline);