TSV 矩阵作为 D3 中的散点图

TSV Matrix as Scatterplot in D3

本文关键字:散点图 D3 TSV      更新时间:2023-09-26

我在 TSV 文件中有一个 1000(行)x100(列)矩阵,其中每个单元格都是一个整数。我想做数据的散点图,X 轴将是行 (1000),列是 Y 轴。每个值将表示为一个圆圈,如果值更大,该圆圈将更大。

起初,我尝试使用 D3 加载数据.js:

 d3.tsv(Data_url, function(matrix_data) {
  console.log((matrix_data));
}

我得到的只是一个包含 1000 个对象的一维数组,我不知道为什么。此外,我想按照前面的说明绘制这些数据,所以我需要行号和列号,因为它们确实是数据。我的意思是,de 0 到 100 列是百分比,0 到 1000 行是长度,所以我需要这样的东西:

    .attr("cx", function (d) { return x(row_number); })
    .attr("cy", function (d) { return y(column_number); })
    .attr("r", function (d) { return r(d); });

但我找不到东西来获得row_number和column_number。我做了另一种使用"Papaparse"来读取数据的方法,它工作正常。即使以这种方式使用 JSON:

 matrix = JSON.parse(JSON.stringify(matrix_data));

我只是想了解在 D3 中应该如何完成它。提前感谢=)

给定以下矩阵状数据:

18  12  14  15  17  14  15  16  16  15  15  14
11  13  15  16  14  14  15  16  16  16  10  18
...

这是绘制它的快速方法:

// grad the data as text
d3.text("data.tsv", function(text) {
  // parse the data, this will produce an array of arrays
  // where the outer array is each row, the inner each column
  var data = d3.tsv.parseRows(text); 
  // set your domains to be the lengths of your data with some padding
  x.domain([-0.5, data.length + 0.5]);
  y.domain([-0.5, data[0].length + 0.5]);
  // we are going to use a nested selection
  // the outer represents a row and is a svg g
  var rows = svg.selectAll(".row")
    .data(data)
    .enter()
    .append('g')
    .attr('class', 'row');
  // the inner selection is a col and contains the points
  // which are circles
  rows.selectAll('.point')
    .data(function(d){
      return d; //<-- return each point
    })
    .enter()
    .append('circle')
    .attr('class', 'point')
    .attr('cx', function(d,i,j){
      return x(j); //<-- the 'j' is the index of the row
    })
    .attr('cy', function(d,i,j){
      return y(i); //<-- the 'i' is the index of the column
    })
    .attr('r', function(d,i,j){
      return d; //<-- the d is the value in the matrix
    })
    .style('fill', 'steelblue');

完整的工作示例在这里。