单击图例时,我正在尝试切换折线图中的数据点。这是我小提琴的link。在我的小提琴上,当单击图例时,线条和相应的轴将会打开和关闭,但点不会。相关代码如下。
//************* Lines and Data Points ***************
var colors = ["blue", "red"];
var thisScale;
var line = d3.line()
.x(d => x(d.x))
.y(d => thisScale(d.y))
.curve(d3.curveLinear);
var paths = g.selectAll("foo")
.data(data)
.enter()
.append("path");
paths.attr("stroke", function (d,i){return colors[i]})
.attr("d", d => {
thisScale = yScale[d.yAxis]
return line(d.data);
})
.attr("stroke-width", 2)
.attr("id", function (d,i){return "line" + i})
.attr("fill", "none");
var pointsGroup = g.selectAll(null)
.data(data)
.enter()
.append("g")
.attr("fill", function(d, i) {
local.set(this, yScale[i])
return colors[i];
});
var points = pointsGroup.selectAll(null)
.data(function(d) {
return d.data
})
.enter()
.append("circle")
.attr("cx", function(d) {
return x(d.x);
})
.attr("cy", function(d, i) {
return local.get(this)(d.y);
})
.attr("r", 3)
.attr("class", function(d, i) {
return "dots" + i;
})
.attr("clip-path", "url(#clip)")
.on("mouseover", mouseover)
.on("mouseleave", mouseleave)
//************* Legend ***************
var legend = svg.selectAll(".legend")
.data(data)
.enter().append("g")
legend.append("rect")
.attr("x", width + 65)
.attr("y", function(d, i) {
return 30 + i * 20;
})
.attr("width", 18)
.attr("height", 4)
.style("fill", function(d, i) {
return colors[i];
})
legend.append("text")
.attr("x", width + 60)
.attr("y", function(d, i) {
return 30 + i * 20;
})
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d, i) {
return "Value" + (i + 1);
})
.on("click", function(d, i) {
// Determine if current line is visible
let opacity = d3.select("#line" + i).style("opacity");
let newOpacity;
if (opacity == 0) {
newOpacity = 1;
}else {
newOpacity = 0
}
d3.select("#line" + i).style("opacity", newOpacity);
d3.selectAll("dots" + i).style("opacity", newOpacity);
d3.select("#ySecAxis" + i).style("opacity", newOpacity);
d3.select("#yAxisLabel" + i).style("opacity", newOpacity);
});
我已经将类归因于我的点数.attr("class", function(d, i) { return "dots" + i; })
,并尝试使用d3.selectAll("dots" + i).style("opacity", newOpacity);
切换点数。但是,它不起作用,有人知道问题出在哪里吗?
发布于 2019-11-14 00:23:14
您需要进行两个更改
1-将dots类分配给父g元素,以便只对每组点迭代i变量。不要在点本身上使用赋值类。
var pointsGroup = g.selectAll(null)
.data(data)
.enter()
.append("g")
.attr("class", function(d, i) {
return "dots" + i
})
.attr("fill", function(d, i) {
local.set(this, yScale[i])
return colors[i];
});
2-通过包括".“来选择点类别。在选择名称中
d3.selectAll(".dots" + i).style("opacity", newOpacity);
https://stackoverflow.com/questions/58830800
复制相似问题