【问题标题】:Filtering by an array in D3 (filtering by array of string keywords)在 D3 中按数组过滤(按字符串关键字数组过滤)
【发布时间】:2019-12-30 05:13:09
【问题描述】:

我正在尝试根据数据属性中是否存在某些关键字来过滤地图上的数据点。例如,按音乐流派过滤点,即显示“流派”属性包含以下任一关键字的所有点:“摇滚”、“流行”、“独立”。

它几乎可以工作,但我不能完全让 D3 过滤器方法在数组上工作。这是一个例子:

//When "Rock Genre" radio button is instantiated, display only "Rock" events
d3.selectAll("#rockPopGenre").on("change", function() {
resetDisplay()
display = this.checked ? "none" : "#ffba00";
display2 = this.checked ? "none" : "black";
x = ["Rock","Pop","Indie"]
genreMatch(x)            
});


//Genre matching function which filters points based on an array of key-words
function genreMatch (genreType) {
var genreType

for (i=0; i<genreType.length; i++){
    d3.selectAll(".events")
.filter(function(d) {       
    return (!d.Genre.includes(genreType[i]))
})
.style("fill", display)
.style("stroke", display2)
}  
}  

d.Genre 示例:

"Genre": "Standup, Comedy Rock, Comedy, Standup Comedy, Funny, Humor"
"Genre": "Genres: Alternative Rock, Alternative, Pop"
"Genre": "Indie, Indie Electronic, Rock, Alternative"

上述方法仅部分有效。例如,它只显示包含关键字“Rock”的点,但会排除包含“Pop”的点。我想根据所有关键字过滤数据:即如果 d.Genre 在字符串中包含“Rock”、“Pop”或“Indie”,则显示这些点,并隐藏不符合该条件的点。

我不太确定如何实现这一点。我认为问题在于代码分别过滤数组中的每个关键字,而不是将数组视为要匹配的一组单词。提前致谢。

【问题讨论】:

  • 你为什么过滤d.Genre而不包括genreType[i]d.Genre 是什么样的?你能发布一个最小的例子吗?
  • 我正在过滤“不包括”,因为对于那些不符合关键字标准的点,我将显示设置为“非”。

标签: javascript arrays d3.js filter


【解决方案1】:

您可以根据过滤器更改事件的不透明度属性:

d3.selectAll(".events").attr('opacity', d => {   
   const includes = genreType.filter(item => d.Genre.indexOf(item) !== -1)
   return includes ? 1 : 0
})

这将适用于假设 d.Genre 是一个字符串 "Standup, Comedy Rock, Comedy, Standup Comedy, Funny, Humor" 并且genreType 是一个关键字数组,例如:["Standup", "Comedy"]

genreType 是另一个字符串,您应该像 .split(/, ?/g) 那样执行拆分以便转换它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2015-12-25
    • 2017-07-15
    • 1970-01-01
    • 2021-09-18
    相关资源
    最近更新 更多