如何使用D3.js筛选数据?

7

我一直在网上搜索,但是我找不到我需要的内容。我想可能是我没有使用正确的术语。

我在D3.js中有一个简单的散点图。我的csv文件如下:

Group, X, Y

1, 4.5, 8
1, 9, 12
1, 2, 19
2, 9, 20
3, 2, 1
3, 8, 2

我希望能够按组进行筛选。因此,默认情况下,图表仅显示组1的值,但您也可以选择查看组2或组3的值。

这里是我已经拥有的一些代码...

var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.linear()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.csv("l2data.csv", function(error, data) {
  if (error) throw error;

  // Coerce the strings to numbers.
  data.forEach(function(d) {
    d.x = +d.x;
    d.y = +d.y;
  });

  // Compute the scales’ domains.
  x.domain(d3.extent(data, function(d) { return d.x; })).nice();
  y.domain(d3.extent(data, function(d) { return d.y; })).nice();

  // Add the x-axis.
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.svg.axis().scale(x).orient("bottom"));

  // Add the y-axis.
  svg.append("g")
      .attr("class", "y axis")
      .call(d3.svg.axis().scale(y).orient("left"));

  // Add the points!
  svg.selectAll(".point")
      .data(data)
    .enter().append("path")
      .attr("class", "point")
      .attr("d", d3.svg.symbol().type("triangle-up"))
      .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
});

2个回答

8
你已经有了一个不错的开端!如果想要更好,需要三个东西:一个用于选择组的UI组件,一个用于检测该组件变化的事件监听器,以及一个用于处理可视化更新的函数。
在我添加的代码中,我创建了三个新函数,对应d3生命周期的每个部分。Enter处理向图形中添加新元素。Update根据绑定数据的变化更新现有值。Exit移除不再绑定数据的任何元素。阅读 Mike Bostock 在https://bost.ocks.org/mike/join/链接中的经典文章以获取更多信息。使用这些功能,您可以为图表添加酷炫的过渡效果,并自定义数据进入和退出的方式。

var data = [{ group: 1, x: 5.5, y: 0 }, { group: 1, x: 0, y: 6 }, { group: 1, x: 7.5, y: 8 }, { group: 2, x: 4.5, y: 4 }, { group: 2, x: 4.5, y: 2 }, { group: 3, x: 4, y: 4 }];

var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.linear()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);
  

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    
// Coerce the strings to numbers.
data.forEach(function(d) {
  d.x = +d.x;
  d.y = +d.y;
});

// Compute the scales’ domains.
x.domain(d3.extent(data, function(d) { return d.x; })).nice();
y.domain(d3.extent(data, function(d) { return d.y; })).nice();


// Add the x-axis.
svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.svg.axis().scale(x).orient("bottom"));

// Add the y-axis.
svg.append("g")
  .attr("class", "y axis")
  .call(d3.svg.axis().scale(y).orient("left"));

// Get a subset of the data based on the group
function getFilteredData(data, group) {
 return data.filter(function(point) { return point.group === parseInt(group); });
}

// Helper function to add new points to our data
function enterPoints(data) {
  // Add the points!
  svg.selectAll(".point")
    .data(data)
    .enter().append("path")
    .attr("class", "point")
    .attr('fill', 'red')
    .attr("d", d3.svg.symbol().type("triangle-up"))
    .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
}

function exitPoints(data) {
  svg.selectAll(".point")
      .data(data)
      .exit()
      .remove();
}

function updatePoints(data) {
  svg.selectAll(".point")
      .data(data)
      .transition()
   .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
}

// New select element for allowing the user to select a group!
var $groupSelector = document.querySelector('.group-select');
var groupData = getFilteredData(data, $groupSelector.value);

// Enter initial points filtered by default select value set in HTML
enterPoints(groupData);

$groupSelector.onchange = function(e) {
  var group = e.target.value;
  var groupData = getFilteredData(data, group);

  updatePoints(groupData);
  enterPoints(groupData);
  exitPoints(groupData);

};
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<label>
  Group
  <select class="group-select">
    <option value=1 selected>1</option>
    <option value=2>2</option>
    <option value=3>3</option>
  </select>
</label>


2

这取决于您需要做什么,但您可以像我根据您的问题制作的以下代码片段中所示那样进行操作。我跳过了数据加载,但原则是相同的。

您必须创建一个变量来保存创建的点,然后使用选择列表或其他东西来根据选择隐藏或显示点。

// this variable will hold your created symbols
var points,
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 400 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

var x = d3.scale.linear()
.range([0, width]);

var y = d3.scale.linear()
.range([height, 0]);

var select = d3.select('body')
    .append('div')
    .append('select')
    .on('change', function(){
      // get selected group
      var group = select.property('value');
      // hide those points based on the selected value.
      points.style('opacity', function(d){
        return d.group == group ? 1:0;
      });
    });

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var data = [
      {group:1, x:4.5, y:8},
      {group:1, x:9, y:12},
      {group:1, x:2, y:19},
      {group:2, x:9, y:20},
      {group:3, x:2, y:1},
      {group:3, x:8, y:2}
    ];

// Coerce the strings to numbers.
data.forEach(function(d) {
  d.x = +d.x;
  d.y = +d.y;
});

var groups = d3.set(data.map(function(d){ return d.group; })).values();

// create group filtering select list
select.selectAll('option')
  .data(groups)
  .enter().append('option').text(function(d){ return d });

select.property('value', groups[0]); // default selected group


// Compute the scales’ domains.
x.domain(d3.extent(data, function(d) { return d.x; })).nice();
y.domain(d3.extent(data, function(d) { return d.y; })).nice();

// Add the x-axis.
svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.svg.axis().scale(x).orient("bottom"));

// Add the y-axis.
svg.append("g")
  .attr("class", "y axis")
  .call(d3.svg.axis().scale(y).orient("left"));

// Add the points!
points = svg.selectAll(".point")
  .data(data)
  .enter().append("path")
    .attr("class", "point")
    .attr("d", d3.svg.symbol().type("triangle-up"))
    .attr("transform", function(d){ 
      return "translate("+x(d.x)+","+y(d.y)+")";
    })
    // hide all points expect default group
    .style('opacity', function(d){ return d.group == groups[0]?1:0; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>


谢谢@PierreB!这非常有帮助。我整个周末都在研究,但一直无法解决问题。感谢您花时间帮助我解决这个问题。 - Alice K.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接