我有一个带有缩放功能的D3 JS散点图,我预先计算了线性回归(OLS),我可以像这样绘制趋势线:
var objects = svg.append("svg")
.classed("objects", true)
.attr("width", width)
.attr("height", height);
var x = d3.scale.linear()
.range([0, width]).nice();
var y = d3.scale.linear()
.range([height, 0]).nice();
objects.append("svg:line")
.classed("trendline", true)
.attr("x1", x(xMin))
.attr("y1", y(lineIntercept + xMin*lineSlope))
.attr("x2", x(xMax))
.attr("y2", y(lineIntercept + xMax*lineSlope))
.attr("stroke", colorVal)
.attr("stroke-width", 2);
这就是我想要的,除了线条从xMin
到xMax
并且我希望它从-Inf转到Inf并且当用户缩小时这变得明显,怎么能我这样做?
答案 0 :(得分:0)
解决方法是(在Q评论中讨论)每次缩放后找出x轴的当前域位置结束(获得调用x.domain()
)然后更新该行。完整的解决方案如下:
objects
.selectAll(".trendline")
.attr("x1", x(x.domain()[0]))
.attr("y1", y(lineIntercept + x.domain()[0]*lineSlope))
.attr("x2", x(x.domain()[1]))
.attr("y2", y(lineIntercept + x.domain()[1]*lineSlope))
.attr("stroke", colorVal)
.attr("stroke-width", 2);
这给人一种视觉印象,即该线从-Inf变为Inf