首页 > 解决方案 > 获取对象的特定属性以进行绘图

问题描述

我正在尝试使用 D3 来绘制与时间相关的数据。我导入的文件有多个通道。我想在图表上显示每个数据通道。

我正在尝试格式化 var "dataset",以便 d3 可以将其识别为要绘制的数字列表。

抓取数据:

var dataset = d3.tsv("/Data/"+`${fridge}`+getInstrumentURL(instrumentArray[1]))
.then( data => 
{ 
    data.forEach( d => 
    {
        d['Date  Time'] = new Date(d['Date  Time']);
        d.Tpt1 = +d.Tpt1;
        d.Tpt2 = +d.Tpt2;
        d.Tstill = +d.Tstill;
        d.Tdblstill = +d.Tdblstill;
        d.Tcp = +d.Tcp;
        d.Tmc = +d.Tmc;
        d.Tsamp = +d.Tsamp;
    }); 
    console.log(data); 
});  // converts strings to numbers. Console log confirms my data transfer.

绘图:

var svg = d3.select("graph").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 + ")");

svg.append("path")  //lines connecting data points
    .datum(dataset)  //here i want to use channel Tpt1, Tpt2, etc.
    .attr("class", "line") 
    .attr("d", line);

svg.selectAll(".dot")  //data POINTS
    .data(dataset)
    .enter().append("circle") // Uses the enter().append() method
    .attr("class", "dot")
    .attr("cx", function(d, i) { return xScale(i) })
    .attr("cy", function(d) { return yScale(d.y) })
    .attr("r", 5)

就像“数据集”:页面加载,图中没有数据。
作为dataset[]['Tpt1']:页面加载不正确
作为dataset['Tpt1']:未定义的错误。我知道为什么这是错误的(索引),但是如何传递整个数组以便绘制每个 Tpt1 值?

我正在尝试使用此 Bl.ocks 示例,但使用 TSV:https ://bl.ocks.org/gordlea/27370d1eea8464b04538e6d8ced3​​9e89

标签: javascriptobjectd3.js

解决方案


我不完全理解这个问题,但看看这一行:

var dataset = d3.tsv('/yourpath...')

你不了解异步tsv()函数是如何工作的,因为它总是会返回 undefined 给dataset变量。数据只有在Promise设置 byd3.tsv()被解析并执行回调函数时才可用then()

您应该将构建可视化的代码放在一个函数中,以便在then()获取数据时可以在函数的回调中调用它,如下所示。

// Define you code that builds the vizualization within a function that
// accepts your dataset as an argument. This function can then be called
// whenever you have access to your data.
function buildMyViz(data) {
  var svg = d3.select('graph')
  ... etc
}

var dataset; // Define dataset outside of your request for data
d3.tsv('/yourpath...').then(function(returnedData) {

  // When the data is returned (asynchronously), you can assign it to dataset
  dataset = returnedData;

  // Now you have the data you can trigger the code that builds the d3 viz
  buildMyViz(dataset);
});

推荐阅读