根据d3js中的数据id选择散点图中的点

时间:2014-04-30 02:14:59

标签: javascript d3.js data-visualization

我最初根据d3js中从服务器获取的数据来填充散点图。现在我打算根据数据ID突出显示点。

样本数据集:

gdata = [{'pid': 161, 'cu': 4, 'ft': 2.8, 'car': 57.1},
        {'pid': 161, 'cu': 4, 'ft': 2.8, 'car': 57.1}
         ]

  func init() {
           // Some code 
         svg.selectAll(".dot")
            .data(gdata)
            .enter().append("svg:circle")
            .attr("class", "dot")
            .attr("r", 5.5)
            .attr("stroke", "")
            .attr("cx", function(d) { return x(d.fats); })
            .attr("cy", function(d) { return y(d.carbs); })
            .style("fill", function(d) { 
                if (d.pid == $('#package_id').val()) {
                       return "red" ;
                }
                return "#1f77b4" ; /*(d.cuisine == 6 ? "#cfcfcf" : color(d.cuisine));*/ 
            });
       }

我正在尝试创建另一个功能

//psuedocode
function highlight(subset) {
      subset =  {'pid': 161, 'cu': 4, 'ft': 2.8, 'car': 57.1} ;
      select that particular dot in scatter plot which represents that data point
      and style("fill", "red")
}

1 个答案:

答案 0 :(得分:1)

由于假定突出显示的点已由init()绘制,因此您无需进行任何数据绑定。相反,您需要根据d选择点并调整其填充,以及它是否显示在subset中:

function highlight(subset) {
  svg.selectAll('.dot').style("fill", function(d) {
    var dIsInSubset = d.pid == subset.pid;
    return dIsInSubset ? 'red' : '#1f77b4'
  })
}