如何使用D3.js过滤数据

How to Filter Data with D3.js?

本文关键字:过滤 数据 js D3 何使用      更新时间:2023-09-26

我一直在网上搜索,但我真的找不到我要找的东西。我想也许我用的术语不对。

我有一个简单的散点图在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) + ")"; });
});

你有一个良好的开端!为了使它更好,你需要三个东西。一个用于选择组的UI组件,一个用于检测该组件更改的事件侦听器,以及一个用于处理可视化更新的函数。

在我添加的代码中,我为d3生命周期的每个部分创建了三个新函数。输入处理向图中添加新元素。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>

这取决于您需要做什么,但您可以像下面我根据您的问题所做的代码片段那样做。我跳过了数据加载,但原理是一样的。

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

// 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>