首先,对于散点图,您将附加到svg。您需要附加到创建路径的同一区域。所以而不是(在第 110 行):
svg.selectAll("dot")
做:
focus.selectAll("dot")
更新小提琴:https://jsfiddle.net/thatoneguy/fmtygLfv/2/
至于点(工具提示)。我已经将点的创建放在这样的函数中:
// Add the scatterplot
function addScatter(){
focus.selectAll(".dot").data(data)
.enter().append("circle").attr('class','dot')
.attr("r", 5)
.attr("cx", function(d) { return x(d.date); })
.attr("cy", function(d) { return y(d.price); })
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div .html(d.date + "<br/>" + d.price)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
}
addScatter()
立即实例化它。现在刷的时候可以用这个。更新画笔:
function brushed() {
x.domain(brush.empty() ? x2.domain() : brush.extent());
focus.select(".area").attr("d", area);
focus.select(".x.axis").call(xAxis);
focus.selectAll(".dot").remove() ; //remove current dots
addScatter()
}
在我打电话给addScatter 之前请注意,我会删除已经存在的点。现在可以正常使用了。
更新小提琴:https://jsfiddle.net/thatoneguy/fmtygLfv/5/
至于您的刻度值。看这个例子:D3 - using strings for axis ticks
目前,您的数据显示的日期范围为 0.2 - 1.0。它们是单个值,而不是它们本身的范围。
所以如果你的数据看起来像这样:
var data = [{ "date":"0.1-0.2", "price":394.46},
{ "date":"0.2-0.3", "price":1366.42},
{ "date":"0.3-0.4", "price":1498.58},
{ "date":"0.4-0.5", "price":1452.43},//and so on
在上面的示例中,您可以像这样使用刻度值:
.tickFormat(function(d, i){
return d.date; // this will return (if data is edited) 0.1-0.2, 0.2-0.3 and so on
})
这意味着编辑您的数据。