如何使用 d3 选择数据中的类别

How to select categories within data using d3

本文关键字:数据 何使用 d3 选择      更新时间:2023-09-26

我是D3的初学者,任何帮助将不胜感激。

在此图表中,为类别"获胜"的每个条目生成一个圆圈。因此,在这种情况下,生成了 4 个半径不同的圆。

我想返回"胜利"的数据

,但只返回"最佳影片"类别的数据。在这种情况下,只会生成 2 个圆圈。这可以通过添加到函数-- .attr('r', function(d) {return radiusScale(d.wins);})来实现,如果是这样,我应该改变什么?

var data = [
        {decade: '1920s', category: 'Best Picture', wins: 2, nominations: 3},
        {decade: '1920s', category: 'Best Director', wins: 1, nominations: 9},
        {decade: '1930s', category: 'Best Picture', wins: 3, nominations: 6},
        {decade: '1930s', category: 'Best Director', wins: 1, nominations: 7},
];
var radiusScale = d3.scale.sqrt().domain([0, 40]).range([0, 40]);

d3.select('svg')
    .selectAll('circle')
    .data(data)
    .enter()
    .append('circle')
    .attr('r', function(d) {return radiusScale(d.wins);})
    .attr('cx', function(d, i) {return i * 80 + 50;})
    .attr('cy', 50);    

使用 .filter() 函数仅获取所需的数据元素:

d3.select('svg')
  .selectAll('circle')
  .data(data.filter(function(d) { return d.category == "Best Picture"; }))
  .enter()
  ...