Javascript d3js v5+;单击图例时显示/隐藏元素
我想要这个反向动作。当我点击我的图例中的一个项目时,我希望集中这些类中地图的所有元素 但是,如何将一个类与其他类进行比较? 例如,在此图像中,仅显示值包含在23500和29000之间的元素,并隐藏其他元素。 我建议1/过滤数据,2/填充这些元素的相同颜色,但肯定更容易。 这是我的密码:Javascript d3js v5+;单击图例时显示/隐藏元素,javascript,d3.js,topojson,Javascript,D3.js,Topojson,我想要这个反向动作。当我点击我的图例中的一个项目时,我希望集中这些类中地图的所有元素 但是,如何将一个类与其他类进行比较? 例如,在此图像中,仅显示值包含在23500和29000之间的元素,并隐藏其他元素。 我建议1/过滤数据,2/填充这些元素的相同颜色,但肯定更容易。 这是我的密码: 你的直觉会起作用-根据颜色过滤路径数据: features.filter(function(feature) { return color(feature.properties["value0"]) ==
你的直觉会起作用-根据颜色过滤路径数据:
features.filter(function(feature) {
return color(feature.properties["value0"]) == d;
})
我将您的功能路径保存在下面的plunkrs中的可变功能中
由于每个图例条目的基准是一种颜色,我们可以根据基准在缩放时产生相同颜色的路径进行过滤。我们也可以指定类名或应用其他指标进行筛选
为事件上的过滤路径上色,还原某类反事件上的所有路径。因为您没有说什么会重置地图,我假设如果您连续两次单击同一个图例条目,地图应该重置(这允许您在每个图例条目之间切换)。为此,我们需要跟踪当前关注的图例条目:
var highlighted = "";
然后,我们只需监听图例条目上的单击事件,然后:
.on("click",function(d,i) {
highlighted = ""; //reset
// revert map back to default state
}
else {
highlighted = d;
// filter features to highlight certain ones.
})
总的来说,这可能看起来像:
.on("click",function(d,i) {
// clicking an active entry: reset:
if(highlighted == d) {
// reset opacity on each path:
features.style("opacity",1);
// reset legend entries' fills:
legend.selectAll("rect")
.style("fill",function(d) { return d; });
// reset highlight variable since nothing is highlighted
highlighted = "";
}
// clicking a different entry: highlight that entry:
else {
//update highlighted variable
highlighted = d;
// set opacity low for all features, filter for chosen features and style accordingly:
features.style("opacity",0.2)
.filter(function(f) {
return color(f.properties["value0"]) == d;
})
.style("opacity",1);
// hollow legend entries
legend.selectAll("rect")
.style("fill","white")
// fill selected option:
d3.select(this).select("rect")
.style("fill",function(d) { return d;});
}
})
看起来像:
(我正在格式化图例条目以显示突出显示的内容-我更改了笔划以适应此情况)
这里有一个更新的
如果您希望能够一次切换多个图例项,那么逻辑将变得更详细,突出显示的变量将成为一个数组
作为鼠标覆盖/关闭事件而不是点击的替代方案(因此无需跟踪活动显示的内容),这里有一个稍微不同的方法,使用相同的原则:
.on("click",function(d,i) {
highlighted = ""; //reset
// revert map back to default state
}
else {
highlighted = d;
// filter features to highlight certain ones.
})
.on("click",function(d,i) {
// clicking an active entry: reset:
if(highlighted == d) {
// reset opacity on each path:
features.style("opacity",1);
// reset legend entries' fills:
legend.selectAll("rect")
.style("fill",function(d) { return d; });
// reset highlight variable since nothing is highlighted
highlighted = "";
}
// clicking a different entry: highlight that entry:
else {
//update highlighted variable
highlighted = d;
// set opacity low for all features, filter for chosen features and style accordingly:
features.style("opacity",0.2)
.filter(function(f) {
return color(f.properties["value0"]) == d;
})
.style("opacity",1);
// hollow legend entries
legend.selectAll("rect")
.style("fill","white")
// fill selected option:
d3.select(this).select("rect")
.style("fill",function(d) { return d;});
}
})